<!--
Before editing this document, please see
https://github.com/w3c/webappsec-trusted-types/blob/master/README.md#spec-changes
-->

<pre class='metadata'>
Title: Trusted Types
Shortname: trusted-types
Group: webappsec
Level: none
Status: ED
URL: https://w3c.github.io/webappsec-trusted-types/dist/spec/
Editor: Krzysztof Kotowicz, Google LLC https://google.com, koto@google.com
Editor: Mike West, Google LLC https://google.com, mkwst@google.com
Repository: w3c/webappsec-trusted-types
Abstract: An API that allows applications to lock down powerful APIs to only accept non-spoofable, typed values in place of strings to prevent vulnerabilities caused by using these APIs with attacker-controlled inputs.
Markup Shorthands: algorithm yes, biblio yes, css no, dfn yes, markdown yes, markup yes
Ignored Terms: h1, h2, h3, h4, h5, h6, xmp, EmptyString
Complain About: missing-example-ids yes
<!-- WPT Path Prefix: /trusted-types/ # Cannot add this, as it requires all the tests to be referenced in the spec -->
</pre>

<pre class="anchors">
urlPrefix: https://html.spec.whatwg.org/multipage/common-dom-interfaces.html; type: dfn; spec: HTML
    text: reflect
url: https://www.w3.org/TR/DOM-Parsing/#h-the-domparser-interface; type: enum; spec: DOM-Parsing
    text: SupportedType
</pre>

<!-- TODO
Complain About: broken-links yes
-->

# Introduction # {#introduction}

*This section is not normative.*

Certain classes of vulnerabilities occur when a web application
takes a value from an attacker-controlled source (e.g. the
document URL parameter, or postMessage channel) and passes that value,
without appropriate sanitization to one of the
[[#injection-sinks|injection sinks]] - various Web API functions with
powerful capabilities.

These types of issues are traditionally difficult to prevent.
Applications commonly call those injection sinks with attacker-controlled
values without authors realizing it, since it's not clear if the
input was attacker-controlled when invoking the injection sink.
Due to the dynamic nature of JavaScript it's also difficult to ascertain
that such pattern is not present in a given program. It is often missed
during manual code reviews, and automated code analysis. As an example,
if `aString` contains untrusted data, `foo[bar] = aString` is a statement
that potentially can trigger a vulnerability, depending on a value
of `foo` and `bar`.

This document focuses on prevening DOM-Based Cross-Site Scripting
that occurs when attacker-controlled data reaches
[[#dom-xss-injection-sinks]], as that eventually causes execution of the
script payload controlled by the attacker. DOM XSS is prevalent in the
web applications as there are over 60 different
injection sinks (e.g. `Element.innerHTML`, or `Location.href` setters).

This document defines [[#trusted-types|Trusted Types]] - an API that allows applications
to lock down [=injection sinks=] to only accept non-spoofable, typed values
in place of strings. These values can in turn only be created from
application-defined [=policies=], allowing the authors to define rules
guarding dangerous APIs, reducing the attack surface to small, isolated parts
of the web application codebase, which are substantially easier to safeguard,
monitor and review.





## Goals ## {#goals}

*   Minimize the likelihood of client-side vulnerabilities that occur when
    calling powerful Web APIs with untrusted data - for example,
    minimize the likelihood of DOM XSS.

*   Encourage a design in which security decisions are
    encapsulated within a small part of the application.

*   Reduce security review surface for complex web application
    codebases.

*   Allow the detection of vulnerabilities similar to how regular
    programming errors are detected and surfaced to the developers, with the
    assist of dynamic and static analysis tools.

## Non-goals ## {#non-goals}

*   Prevent, or mitigate the result of injections into server-side generated
    markup, in specific reflections into the body of the scripts running in a
    document. To address server-side XSS vectors, we recommend existing
    solutions like templating systems or [[CSP3|CSP]]
    [=script-src=].
*   Address resource confinement, e.g. to prevent data exfiltration, or
    connecting to external sources via [[Fetch]].
*   Control subresource loading. Trusted Types aim to allow the authors to
    control loading resources that can script the current document, but not
    other subresources.
*   Prevent *cross-origin* JavaScript execution (for example, Trusted Types
    don't guard loading new documents with JavaScript code via `data:` URLs).
*   Prevent malicious authors of the web application's JavaScript code
    from being able to bypass the restrictions; attempting to protect against
    malicious authors would result in an overtly complex and not-practical
    design.

## Use cases ## {#use-cases}

*   An author maintains a complex web application written in a framework
    that uses a secure templating system to generate the UI
    components. The application also depends on 3rd party client-side
    libraries that perform auxiliary tasks (e.g. analytics, performance
    monitoring). To ensure that none of these components introduce DOM
    XSS vulnerabilities, author defines a Trusted Type policy in the
    templating library and enables the enforcement for the [=DOM XSS injection sinks=].

*   An existing web application interacts with the DOM mostly using XSS-safe
    patterns (i.e. withour using [=DOM XSS injection sinks=]). In a few places,
    however, it resorts to using risky patterns like loading additional script using
    JSONP, calling into `innerHTML` or `eval`.

    Review finds that those places do not cause XSS (e.g. because
    user-controlled data is not part of the input to those sinks), but it's
    hard to migrate the application off using these patterns.

    As such, CSP cannot be enforced on this application (without resorting to
    an unsafe version using `'unsafe-eval' 'unsafe-inline'`). Additionally,
    it's possible some codebase with DOM XSS flaws was not included in a review,
    or will be introduced in the future.

    To address this risk, the author converts the reviewed parts to using
    Trusted Types, and enables Trusted Type [=enforcement=]. Addditional places
    using the injection sinks, should they exist in the future, are correctly
    blocked and reported.

*   A security team is tasked with assuring that the client-side heavy
    application code does not contain XSS vulnerabilities. Since the server side
    code is homogeneous (it's moslty an API backend), and the application
    enforces Trusted Types, the review only focuses on the Trusted Type
    [=policies=] and their rules. Later on the reviewed policy names are
    allowed in the 'trusted-types' CSP directive, safe for the developers to
    use.

    Any additonal code, including the code of often-changing dependencies,
    can be excluded from the review, unless it creates a Trusted Type policy.
    Without it, the code cannot cause a DOM XSS.

# Framework # {#framework}

## Injection sinks ## {#injection-sinks}

*This section is not normative.*

An <dfn>injection sink</dfn> is a powerful Web API function that should only
be called with trusted, validated or appropriately sanitized input.
Calling the injection sink with attacker-controlled (i.e. injected) inputs
has undesired consequences and is considered a security vulnerability.

Note: The exact list of injection sinks covered by this document is defined in
[[#integrations]].

It's difficult to determine if a given application contains such a
vulnerability (e.g. if it is vulnerable to DOM XSS) only by analyzing
the invocations of [=injection sinks=], as their inputs (usually strings)
do not carry the information about their provenance. For example, while
the application might intentionally call `eval()` with dynamically created
inputs (e.g. for code obfuscation purposes), calling `eval()` on strings
supplied by the attacker is definitely a security vulnerability - but
it's not easy to distinguish one from the other.

This document organizes the injection sinks into groups, based on the
capabilities that sinks in a given group have. [=Enforcement=] for groups is controlled via <a>trusted-types-sink-group</a> values.

### HTML injection sinks ### {#html-injection-sinks}

*This section is not normative.*

HTML <a>injection sinks</a> parse input strings into a DOM tree. Since HTML parsers
can create arbitrary elements, including scripts, and set arbitrary attributes,
enabling the [=enforcement=] of any <a>trusted-types-sink-group</a> also implies
enforcing types for HTML injection sinks.

Examples of HTML injection sinks include:

  * Functions that parse & insert HTML strings into the document like
    [[DOM-Parsing#widl-Element-innerHTML|Element.innerHTML]],
    [[DOM-Parsing#widl-Element-outerHTML|Element.outerHTML]] setter, or {{Document/write|Document.write}}.
  * Functions that create a new same-origin {{Document}} with caller-controlled
    markup like {{DOMParser/parseFromString()}},

### DOM XSS injection sinks ### {#dom-xss-injection-sinks}

*This section is not normative.*

DOM XSS <a>injection sinks</a>  evaluate an input string value in a way that could
result in DOM XSS if that value is untrusted.

Examples of include:

  * Setters for {{Element}} attributes that accept a URL of the code to load
    like {{HTMLScriptElement/src!!attribute|HTMLScriptElement.src}},
  * Setters for {{Element}} attributes that accept a code to execute like
    {{HTMLScriptElement/text!!attribute|HTMLScriptElement.text}},
  * Functions that execute code directly like `eval`,
  * Navigation to 'javascript:' URLs.

Guarding DOM XSS injection sinks is controlled by the <a>trusted-types-sink-group</a> named 'script'.

## Trusted Types ## {#trusted-types}

To allow the authors to control values reaching injection sinks,
we introduce [[#trusted-types]]. The following list of
<dfn>Trusted Type</dfn>s indicating that a given value is
trusted by the authors to be used with an [=injection sink=] in a certain context.

Note: **Trusted** in this context signifies the fact that the application author
is confident that a given value can be safely used with an injection sink - she
*trusts* it does not introduce a vulnerability. That does not imply that the
value is indeed *safe*.

Note: This allows the authors to specify the intention when creating a given
value, and the user agents to introduce checks based on the type of
such value to preserve the authors' intent. For example, if
authors intend a value to be used as an HTML snippet, an attempt to
load a script from that value would fail.

Note: All Trusted Types wrap over an immutable string, specified when the
objects are created. These objects are unforgeable in a sense that
there is no JavaScript-exposed way to replace the inner string value
of a given object - it's stored in an internal slot with no setter
exposed.

Note: All Trusted Types stringifiers return the inner string value.
This makes it easy to incrementally migrate the application code into using
Trusted Types in place of DOM strings (it's possible to start
producing types in parts of the application, while still using and
accepting strings in other parts of the codebase). In that sense,
Trusted Types are backwards-compatible with the regular DOM APIs.

### <dfn type>TrustedHTML</dfn> ### {#trusted-html}

The TrustedHTML interface represents a string that a developer can
confidently insert into an [=injection sink=] that will render it as HTML.
These objects are immutable
wrappers around a string, constructed via a {{TrustedTypePolicy}}'s
{{TrustedTypePolicy/createHTML(input)|createHTML}} method.

<pre class="idl">
[Exposed=Window]
interface TrustedHTML {
  stringifier;
};
</pre>

TrustedHTML objects have a `[[Data]]` internal slot which holds a
DOMString. The slot's value is set when the object is created, and
will never change during its lifetime.

To stringify a TrustedHTML object, return the DOMString from its
`[[Data]]` internal slot.

### <dfn type>TrustedScript</dfn> ### {#trusted-script}

The TrustedScript interface represents a string with an uncompiled
script body that a developer can confidently pass into an [=injection sink=]
that might lead to executing that script.
These objects are immutable wrappers
around a string, constructed via a {{TrustedTypePolicy}}'s
{{TrustedTypePolicy/createScript(input)|createScript}} method.

<pre class="idl">
[Exposed=Window]
interface TrustedScript {
  stringifier;
};
</pre>

TrustedScript objects have a `[[Data]]` internal slot which holds a
DOMString. The slot's value is set when the object is created, and
will never change during its lifetime.

To stringify a TrustedScript object, return the DOMString from its
`[[Data]]` internal slot.


### <dfn type>TrustedScriptURL</dfn> ### {#trused-script-url}

The TrustedScriptURL interface represents a string that a developer
can confidently pass into an [=injection sink=] that will parse it as a URL of
an external script resource.
These objects are immutable wrappers around a
string, constructed via a {{TrustedTypePolicy}}'s
{{TrustedTypePolicy/createScriptURL(input)|createScriptURL}} method.

<pre class="idl">
[Exposed=Window]
interface TrustedScriptURL {
  stringifier;
};
</pre>

TrustedScriptURL objects have a `[[Data]]` internal slot which holds a
USVString. The slot's value is set when the object is created, and
will never change during its lifetime.

To stringify a TrustedScriptURL object, return the USVString from its
`[[Data]]` internal slot.


## <dfn>Policies</dfn> ## {#policies-hdr}

Trusted Types can only be created via user-defined
and immutable policies that define rules for converting a string into
a given Trusted Type object. Policies allows the authors to specify custom,
programmatic rules that Trusted Types must adhere to.

<div class="example" id="sanitizing-policy">
Authors may define a
policy that will sanitize an HTML string, allowing only a subset of
tags and attributes that are known not to cause JavaScript
execution. Any {{TrustedHTML}} object created through this policy can then
be safely used in the application, and e.g. passed to `innerHTML`
setter - even if the input value was controlled by the attacker, the
policy rules neutralized it to adhere to policy-specific
contract.
<xmp highlight=js>
const sanitizingPolicy = trustedTypes.createPolicy('sanitize-html', {
  createHTML: (input) => myTrustedSanitizer(input, { superSafe: 'ok'}),
});

myDiv.innerHTML = sanitizingPolicy.createHTML(untrustedValue);
</xmp>
</div>

Note: [=Trusted Type=] objects wrap values that are explicitly trusted by
the author. As such, creating a Trusted Type object instance becomes a de
facto [=injection sink=], and hence code that creates a Trusted Type
instances is security-critical. To allow for strict control over Trusted Type
object creation we don't expose the constructors of those
directly, but require authors to create them via [=policies=].

Multiple policies can be created in a given [=Realm=], allowing the
applications to define different rules for different parts of the
codebase.

<div class="example" id="policy-reference">
Library initialized with a policy allowing it to load additional scripts from
a given host.
<xmp highlight=js>

const cdnScriptsPolicy = trustedTypes.createPolicy('cdn-scripts', {
  createScriptURL(url) {
    const parsed = new URL(url, document.baseURI);
    if (parsed.origin == 'https://mycdn.example') {
      return url;
    }
    throw new TypeError('invalid URL');
  },
});

myLibrary.init({policy: cdnScriptsPolicy});
</xmp>
</div>

Note: Trusted Type objects can only be created via policies. If
[=enforcement=] is enabled, only the policy code can trigger an action
of an [=injection sink=] and hence call-sites of the policies' `create*`
functions are the *only* security-sensitive code in the entire program
with regards to the actions of the [=injection sinks=].
Only this typically small subset of the entire code base needs to be
security-reviewed - there's no need to monitor or review
the [=injection sinks=] themselves, as User Agents [=enforcement|enforce=] that
those sinks will only accept matching Trusted Type objects, and these in turn
can only be created via policies.

The {{TrustedTypePolicyFactory/createPolicy()|createPolicy}} function returns a policy object which `create*` functions
will create Trusted Type objects after applying the policy
rules.

Note: While it's safe to freely use a policy that sanitizes its input anywhere in the application,
there might be a need to create lax policies to be used internally, and only to be
called with author-controlled input. For example, a client-side HTML
templating library, an HTML sanitizer library, or a JS asynchronous
code plugin loading subsystem each will likely need full control over
HTML or URLs. The API design facilitates that - each policy may only
be used if the callsite can obtain a reference to the policy (a return
value from {{TrustedTypePolicyFactory/createPolicy()}}). As such, policy
references can be treated as
<a href="https://en.wikipedia.org/wiki/Object-capability_model">capabilities</a>,
access to which can be controlled using JavaScript techniques
(e.g. via closures, internal function variables, or modules).

<div class="example" id="policy-capability">
Unsafe no-op policy reachable only from within a single code block to ascertain
that it's called only with no attacker-controlled values.
<xmp highlight=js>
(function renderFootnote() {
  const unsafePolicy = trustedTypes.createPolicy('html', {
    createHTML: input => input,
  });
  const footnote = await fetch('/footnote.html').then(r => r.text());
  footNote.innerHTML = unsafePolicy.createHTML(footnote);
})();
</xmp>
</div>

### <dfn type>TrustedTypePolicyFactory</dfn> ### {#trusted-type-policy-factory}

TrustedTypePolicyFactory creates
{{TrustedTypePolicy|policies}} and verifies that Trusted Type object instances
were created via one of the policies.

Note: This factory object is exposed to JavaScript through `window.trustedTypes`
reference - see [[#extensions-to-the-window-interface]].

<pre class="idl">
[Exposed=Window] interface TrustedTypePolicyFactory {
    [Unforgeable] TrustedTypePolicy createPolicy(
        DOMString policyName, optional TrustedTypePolicyOptions policyOptions);
    [Unforgeable] sequence&lt;DOMString> getPolicyNames();
    [Unforgeable] boolean isHTML(any value);
    [Unforgeable] boolean isScript(any value);
    [Unforgeable] boolean isScriptURL(any value);
    [Unforgeable] readonly attribute TrustedHTML emptyHTML;
    [Unforgeable] readonly attribute TrustedScript emptyScript;
    DOMString? getAttributeType(
        DOMString tagName,
        DOMString attribute,
        optional DOMString elementNs = "",
        optional DOMString attrNs = "");
    DOMString? getPropertyType(
        DOMString tagName,
        DOMString property,
        optional DOMString elementNs = "");
    readonly attribute TrustedTypePolicy? defaultPolicy;
};
</pre>

Internal slot `[[DefaultPolicy]]` may contain a {{TrustedTypePolicy}} object,
and is initially empty.

Internal slot `[[CreatedPolicyNames]]` is an <a>ordered set</a> of strings,
initially empty.

<div dfn-type="method" dfn-for="TrustedTypePolicyFactory">

:   <dfn>createPolicy(policyName, policyOptions)</dfn>
::  Creates a policy object that will implement the rules
    passed in the {{TrustedTypePolicyOptions}} |policyOptions| object.
    The allowed policy names may be restricted by [[#content-security-policy-hdr|Content Security Policy]].
    If the policy name is not on the whitelist defined in the [=trusted-types-directive|trusted-types=] CSP directive,
    the policy creation fails with a [[WebIDL-1#idl-Error|TypeError]].
    Also, if unique policy names are enforced (i.e. `'allow-duplicates'` is not used),
    and `createPolicy` is called more than once with any given `policyName`,
    policy creation fails with a TypeError.

    <div class="example" id="create-policy-example">
    <xmp highlight=js>
    // HTTP Response header: Content-Security-Policy: trusted-types foo
    trustedTypes.createPolicy("foo", {}); // ok.
    trustedTypes.createPolicy("bar", {}); // throws - name not on the whitelist.
    trustedTypes.createPolicy("foo", {}); // throws - duplicate name.
    </xmp>
    </div>

    Returns the result of executing a [$Create a Trusted Type Policy$] algorithm,
    with the following arguments:
    <dl>
    <dt>factory</dt>
    <dd>[=context object=]</dd>
    <dt>policyName</dt>
    <dd>|policyName|</dt>
    <dt>options</dt>
    <dd>|policyOptions|</dd>
    <dt>global</dt>
    <dd>[=context object=]'s [=relevant global object=]</dd>
    </dl>

    <div class="example" id="create-and-used-unexposed-policy">
    <xmp highlight="js">
    const myPolicy = trustedTypes.createPolicy('myPolicy', {
      // This security-critical code needs a security review;
      // a flaw in this code could cause DOM XSS.
      createHTML(input) { return aSanitizer.sanitize(input) },
      createScriptURL(input) {
        const u = new URL(dirty, document.baseURI);
        if (APPLICATION_CONFIG.scriptOrigins.includes(u.origin)) {
          return u.href;
        }
        throw new Error('Cannot load scripts from this origin');
      },
    });

    document.querySelector("#foo").innerHTML = myPolicy.createHTML(aValue);
    scriptElement.src = myPolicy.createScriptURL(
        'https://scripts.myapp.example/script.js');
    </xmp>
    </div>


: <dfn>getPolicyNames()</dfn>
::  This function returns the names of all the policies that were already created.

    Returns a new list, comprising of all entries  of the
    `[[CreatedPolicyNames]]` slot.

    <div class="example" id="get-policy-names-example">
    <xmp highlight=js>
    trustedTypes.createPolicy('foo', ...);
    trustedTypes.createPolicy('bar', ...);
    trustedTypes.getPolicyNames(); // ['foo', 'bar']
    </xmp>
    </div>


: <dfn>isHTML(value)</dfn>
:: Returns true if value is an instance of {{TrustedHTML}} and has its `[[Data]]`  internal slot set, false otherwise.

    Note: `is*` functions are used to check if a given object is truly a legitimate
    [=Trusted Type=] object (i.e. it was created via one of the configured
    policies). This is to be able to detect a forgery of the objects via
    e.g. [[ECMASCRIPT#sec-object.create|Object.create]]
    or prototype chains manipulation.

    <div class="example" id="is-html-example">
    <xmp highlight=js>
    const html = policy.createHTML('<div>');
    trustedTypes.isHTML(html); // true

    const fake = Object.create(TrustedHTML.prototype);
    trustedTypes.isHTML(fake); // false

    trustedTypes.isHTML("<div>plain string</div>"); // false
    </xmp>
    </div>


: <dfn>isScript(value)</dfn>
:: Returns true if value is an instance of {{TrustedScript}} and has its `[[Data]]` internal slot set, false otherwise.

: <dfn>isScriptURL(value)</dfn>
:: Returns true if value is an instance of {{TrustedScriptURL}} and has its `[[Data]]` internal slot set, false otherwise.

: <dfn>getPropertyType(tagName, property, elementNs)</dfn>
:: Allows the authors to check if a Trusted Type is required for a given {{Element}}'s
    property (IDL attribute).

    This function returns the result of the following algorithm:

    1. Set |localName| to |tagName| in [=ASCII lowercase=].
    1. If |elementNs| is an empty string, set |elementNs| to [=HTML namespace=].
    1. Let |interface| be the [=element interface=] for |localName| and |elementNs|.
    1. If |interface| has an IDL [=attribute=] member which identifier is |attribute|, and
        {{TrustedTypes}} IDL extended attribute appears on that attribute, return
        stringified {{TrustedTypes}}'s identifier and abort futher steps.

        Note: This also takes into account all members of [=interface mixins=] that
        |interface| [=includes=].

    1. Return null.

    <div class="example" id="get-property-type-example">
    <xmp highlight="js">
    trustedTypes.getPropertyType('div', 'innerHTML'); // "TrustedHTML"
    trustedTypes.getPropertyType('foo', 'bar'); // undefined
    </xmp>
    </div>


: <dfn>getAttributeType(tagName, attribute, elementNs, attrNs)</dfn>
:: Allows the authors to check if, (and if so, which) Trusted Type is required
    for a given {{Element}}'s [=content attribute=], such that later on the call
    to `Element.setAttribute` passes the correct argument type.

    This function returns the result of the following algorithm:

    1. Set |localName| to |tagName| in [=ASCII lowercase=].
    1. Set |attribute| to |attribute| in [=ASCII lowercase=].
    1. If |elementNs| is an empty string, set |elementNs| to [=HTML namespace=].
    1. If |attrNs| is an empty string, set |attrNs| to null.
    1. Let |interface| be the [=element interface=] for |localName| and |elementNs|.
    1. If |interface| does not have an IDL [=attribute=] that [=reflects=] a content attribute with
        |localName| [=attribute/local name=] and |attrNs| [=attribute/namespace=],
        return undefined and abort further steps. Otherwise, let |idlAttribute| be that IDL [=attribute=].
    1. If {{TrustedTypes}} IDL extended attribute appears on |idlAttribute|, return
        stringified {{TrustedTypes}}'s identifier and abort futher steps.
    1. Return null.

    <div class="example" id="get-attribute-type-example">
    <xmp highlight="js">
    trustedTypes.getAttributeType('script', 'SRC'); // "TrustedScriptURL"
    trustedTypes.getAttributeType('foo', 'bar'); // undefined
    </xmp>
    </div>

</div>

<div dfn-type="attribute" dfn-for="TrustedTypePolicyFactory">

: <dfn>emptyHTML</dfn>
:: is a {{TrustedHTML}} object with its `[[Data]]` internal slot value set to an empty string.

<div class="example" id="empty-html-example">
<xmp highlight="js">
anElement.innerHTML = trustedTypes.emptyHTML; // no need to create a policy
</xmp>
</div>

: <dfn>emptyScript</dfn>
:: is a {{TrustedScript}} object with its `[[Data]]` internal slot value set to an empty string.

Note: This object can be used to detect if the runtime environment has [[#csp-eval]]. While native Trusted Types implementation can
support `eval(TrustedScript)`, it is impossible for a polyfill to  emulate that, as
eval(TrustedScript) will return its input without unwrapping and evaluating the code.

<div class="example" id="empty-script-example">
<xmp highlight="js">
// With native Trusted Types support eval(trustedTypes.emptyScript) will execute and return falsy undefined.
// Without it, eval(trustedTypes.emptyScript) will return a truthy Object.
const supportsTS = !eval(trustedTypes.emptyScript);

eval(supportsTS ? myTrustedScriptObj : myTrustedScriptObj.toString());
</xmp>
</div>

: <dfn>defaultPolicy</dfn>
:: Returns the value of `[[DefaultPolicy]]` internal slot, or null if the slot is empty.

<div class="example" id="defaultpolicy-example">
<xmp highlight="js">
trustedTypes.defaultPolicy === null;  // true
const dp = trustedTypes.createPolicy('default', {});
trustedTypes.defaultPolicy === dp;  // true
</xmp>
</div>

</div>

### <dfn type>TrustedTypePolicy</dfn> ### {#trusted-type-policy}

Policy objects implement a TrustedTypePolicy interface and define a
group of functions creating Trusted Type objects.
Each of the `create*` functions converts a string value to a given Trusted Type variant, or
throws a TypeError if a conversion of a given value is disallowed.

<pre class="idl">
[Exposed=Window]
interface TrustedTypePolicy {
  [Unforgeable] readonly attribute DOMString name;
  [Unforgeable] TrustedHTML createHTML(DOMString input, any... arguments);
  [Unforgeable] TrustedScript createScript(DOMString input, any... arguments);
  [Unforgeable] TrustedScriptURL createScriptURL(DOMString input, any... arguments);
};
</pre>

Each policy has a <dfn dfn-for="TrustedTypePolicy">name</dfn>.

Each TrustedTypePolicy object has an `[[options]]` internal slot, holding the {{TrustedTypePolicyOptions}} object describing the actual behavior of the policy.

<div dfn-type="method" dfn-for="TrustedTypePolicy">

: <dfn>createHTML(input, ...arguments)</dfn>
::  Returns the
    result of executing the [$Create a Trusted Type$] algorithm, with the
    following arguments:
    <dl>
      <dt>policy</dt>
      <dd>[[DOM#context-object|context object]]</dt>
      <dt>trustedTypeName</dt>
      <dd>`"TrustedHTML"`</dd>
      <dt>value</dt>
      <dd>input</dd>
      <dt>arguments</dt>
      <dd>arguments</dd>
    </dl>

: <dfn>createScript(input, ...arguments)</dfn>
::  Returns the
    result of executing the [$Create a Trusted Type$] algorithm, with the
    following arguments:
    <dl>
      <dt>policy</dt>
      <dd>[[DOM#context-object|context object]]</dt>
      <dt>trustedTypeName</dt>
      <dd>`"TrustedScript"`</dd>
      <dt>value</dt>
      <dd>input</dd>
      <dt>arguments</dt>
      <dd>arguments</dd>
    </dl>


: <dfn>createScriptURL(input, ...arguments)</dfn>
::  Returns the
    result of executing the [$Create a Trusted Type$] algorithm, with the
    following arguments:
    <dl>
      <dt>policy</dt>
      <dd>[[DOM#context-object|context object]]</dt>
      <dt>trustedTypeName</dt>
      <dd>`"TrustedScriptURL"`</dd>
      <dt>value</dt>
      <dd>input</dd>
      <dt>arguments</dt>
      <dd>arguments</dd>
    </dl>

</div>

### <dfn type>TrustedTypePolicyOptions</dfn> ### {#trusted-type-policy-options}

This dictionary holds author-defined functions for converting string
values into trusted values. These functions do not create [=Trusted Type=]
object instances directly - this behavior is provided by
{{TrustedTypePolicy}}.

<pre class="idl">
dictionary TrustedTypePolicyOptions {
   CreateHTMLCallback? createHTML;
   CreateScriptCallback? createScript;
   CreateScriptURLCallback? createScriptURL;
};
callback CreateHTMLCallback = DOMString (DOMString input, any... arguments);
callback CreateScriptCallback = DOMString (DOMString input, any... arguments);
callback CreateScriptURLCallback = USVString (DOMString input, any... arguments);
</pre>

### <dfn>Default policy</dfn> ### {#default-policy-hdr}

*This section is not normative.*

One of the policies, the policy with a [=TrustedTypePolicy/name=] `"default"`, is special;
When an [=injection sink=] is passed a string (instead of a
Trusted Type object), this policy will be implicitly called by
the user agent with the string value as the first argument, and the sink name
as a second argument.

This allows the application to define a fallback behavior to use instead of
causing a violation. The intention is to allow the applications to recover from
an unexpected data flow, and sanitize the
potentially attacker-controlled string "as a last resort", or reject a value
if a safe value cannot be created. Errors thrown from within a policy are
propagated to the application.

If the default policy doesn't exist, or if its appropriate `create*` function
returns *null* or *undefined*, it will cause a CSP violation. In the
enforcing mode, an error will be thrown, but in report-only the original value
passed to the default policy will be used.

Note: This optional behavior allows for introducing Trusted Type [=enforcement=]
to applications that are still using legacy code that uses injection sinks.
Needless to say, this policy should
necessarily be defined with very strict rules not to bypass the security
restrictions in unknown parts of the application. In an extreme
case, a lax, no-op default policy defeats all the benefits of using Trusted Types
to protect access to [=injection sinks=]. If possible,
authors should resort to a default policy in a transitional period
only, use it to detect and rewrite their dependencies that use injection
sinks unsafely and eventually phase out the usage of the default policy entirely.

Note: See [[#get-trusted-type-compliant-string-algorithm]] for details on how
the default policy is applied.

<div class="example" id="default-policy-example">
<xmp highlight="js">
// Content-Security-Policy: trusted-types default; require-trusted-types-for 'script'

trustedTypes.createPolicy('default', {
  createScriptURL: (s, sink) => {
    console.log("Please refactor.");
    return s + "?default-policy-used&sink=" + encodeURIComponent(sink);
  }
});

aScriptElement.src = "https://cdn.example/script.js";
// Please refactor.
console.log(aScriptElement.src);
// https://cdn.example/script.js?default-policy-used&sink=script.src
</xmp>
</div>


## <dfn>Enforcement</dfn> ## {#enforcement-hdr}

Note: Enforcement is the process of checking that a value
has an appropriate type before it reaches an [=injection sink=].

The JavaScript API that allows authors to create policies and Trusted Types objects from them is always
available (via {{Window/trustedTypes}}). Since [=injection sinks=] stringify their security sensitive
arguments, and [=Trusted Type=] objects stringify to their inner string values, this allows the authors
to use Trusted Types in place of strings.

To secure the access to [=injection sinks=], on top of the JavaScript code using the Trusted Types,
the user agent needs to enforce them i.e. assert that the injection sinks from a given group are *never*
called with string values, and Trusted Type values are used instead. This section describes how authors
may control this enforcing behavior.

Authors may also control their [=policies=] by specifying rules around policy creation.

### Content Security Policy ### {#content-security-policy-hdr}

Applications may control Trusted Type enforcement via [[CSP#policy-delivery|configuring a Content Security Policy]]. This document defines new directives that correspond to Trusted Types rules.
The [[#require-trusted-types-for-csp-directive|require-trusted-types-for]] directive specifies the [=injection sinks=] groups, for which the types should be required. The [[#trusted-types-csp-directive|trusted-types]] directive controls how [=policies=] can be created.

Note: Using CSP mechanisms allows the authors to prepare their application for enforcing Trusted Types
via using the {{CSP#cspro-header|Content-Security-Report-Only}} HTTP Response header.

Note: Most of the enforcement rules are defined as modifications of the
algorithms in other specifications, see [[#integrations]].

### TrustedTypes extended attribute ### {#!trustedtypes-extended-attribute}

Note: This section describes the implementation details of the Trusted Types mechanism. IDL extended attributes are not exposed to the JavasScript code.

To annotate the [=injection sink=] functions that require Trusted Types, we introduce
<dfn data-dfn-type="extended-attribute" data-x="TrustedTypes" data-lt="TrustedTypes"><code>[TrustedTypes]</code></dfn>
IDL [=extended attributes|extended attribute=]. Its presence indicates that the relevant construct is to be supplemented with additional
Trusted Types enforcement logic.

The {{TrustedTypes}} extended attribute [=extended attribute/takes an identifier=] as an argument.
The only valid values for the identifier are {{TrustedHTML}}, {{TrustedScript}}, or {{TrustedScriptURL}}.
This extended attribute must not appear on anything other than an [=attribute=] or an [=operation=] argument.
Additionally, it must not appear on [=read only=] attributes.

When the extended attribute appears on an attribute, the setter for that attribute must run the following steps in place of the ones specified in its description:

 1. If [=context object=]'s [=relevant global object=] has a [=Window/trusted type policy factory=]:

    Issue: Update when workers have TT.
    1. If the [=context object=] is an {{Element}}, let |objectName| be the [=context object=]'s [=Element/local name=]; Otherwise, let |objectName| be the [=context object=]'s constructor name.
    1. Set |sink| to the result of [=concatenating=] the list &laquo; |objectName|, [=attribute=] identifier. &raquo; with `"."` as |separator|.
        <div class="example" id="extended-attribute-attribute-example">
        For example, the following annotation and JavaScript code:
        <pre highlight=idl>
        partial interface mixin HTMLScriptElement {
          [CEReactions, TrustedTypes=TrustedScriptURL] attribute ScriptURLString src;
        };
        </pre>
        <pre highlight=js>
        document.createElement('script').src = foo;
        document.createElement('script').setAttribute('SrC', foo);
        </pre>
        causes the |sink| value to be `"script.src"`.
        </div>
    1. Set |value| to the result of running the [$Get Trusted Type compliant string$] algorithm, passing the following arguments:
        * the new value as |input|,
        * {{TrustedTypes}} extended attribute identifier as |expectedType|,
        * |sink| as |sink|,
        * `'script'` as |sinkGroup|,
        * [=context object=]'s [=relevant global object=] as |global|.

        Issue: Remove hardcoding 'script' when new sink groups are specified.

    1. If an exception was thrown, rethrow exception and abort further steps.
 1. Run the originally specified steps for this construct, using |value| as a new value to set.

Note: If the IDL attribute [=reflect/reflects=] a content attribute, identical steps should be performed when that content attribute is modified by JavaScript code e.g. via `Element.setAttribute()` function.

When the extended attribute appears on an [=operation=] argument, before its operation is invoked, run the following steps:

 1. If [=context object=]'s [=relevant global object=] has a [=Window/trusted type policy factory=]:

    Issue: Update when workers have TT.
    1. If the [=context object=] is an {{Element}}, let |objectName| be the [=context object=]'s [=Element/local name=]; Otherwise, let |objectName| be the [=context object=]'s constructor name.
    1. Set |sink| to the result of [=concatenating=] the list &laquo; |objectName|, [=operation=] identifier. &raquo; with `"."` as |separator|.
        <div class="example" id="extended-attribute-operation-example">
        For example, the following annotation and JavaScript code:
        <pre highlight=idl>
        partial interface Element {
          void insertAdjacentHTML(DOMString position, [TrustedTypes=TrustedHTML] HTMLString text);
        };
        </pre>
        <pre highlight=js>
        document.createElement('a').insertAdjacentHTML('beforebegin', foo);
        </pre>
        causes the |sink| value to be `"a.insertAdjacentHTML"`.
        </div>
    1. Set the new argument value to the result of running the [$Get Trusted Type compliant string$] algorithm, passing the following arguments:
        * the argument value as |input|,
        * {{TrustedTypes}} extended attribute identifier as |expectedType|,
        * |sink| as |sink|,
        * `'script'` as |sinkGroup|,
        * [=context object=]'s [=relevant global object=] as |global|.

        Issue: Remove hardcoding 'script' when new sink types are specified.

    1. If an exception was thrown, rethrow exception and abort further steps.
 1. Invoke the originally specified steps for the operation.

# Algorithms # {#algorithms}

## <dfn abstract-op>Create a Trusted Type Policy</dfn> ## {#create-trusted-type-policy-algorithm}

To create a {{TrustedTypePolicy}}, given a {{TrustedTypePolicyFactory}} (|factory|),
a string (|policyName|), {{TrustedTypePolicyOptions}} dictionary (|options|), and a
[=Realm/global object=] (|global|) run these steps:

1.  Let |allowedByCSP| be the result of executing [$Should Trusted Type policy
    creation be blocked by Content Security Policy?$] algorithm with |global|,
    |policyName| and |factory|'s `[[CreatedPolicyNames]]` slot value.
1.  If |allowedByCSP| is `"Blocked"`, throw a {{TypeError}} and abort further steps.
1.  If |policyName| is `default` and the |factory|'s `[[DefaultPolicy]]` slot
    value is not empty, throw a {{TypeError}} and abort further steps.
1.  Let |policy| be a new {{TrustedTypePolicy}} object.
1.  Set |policy|'s `name` property value to |policyName|.
1.  Let |policyOptions| be a new {{TrustedTypePolicyOptions}} object.
1.  Set |policyOptions|
    {{TrustedTypePolicy/createHTML()|createHTML}} property to |option|'s
    {{TrustedTypePolicyOptions/createHTML|createHTML}} property value.
1.  Set |policyOptions| {{TrustedTypePolicy/createScript()|createScript}}
    property to |option|'s
    {{TrustedTypePolicyOptions/createScript|createScript}} property value.
1.  Set |policyOptions| {{TrustedTypePolicy/createScriptURL()|createScriptURL}}
    property to |option|'s
    {{TrustedTypePolicyOptions/createScriptURL|createScriptURL}} property value.
1.  Set |policy|'s `[[options]]` internal slot value to *policyOptions*.
1.  If the |policyName| is `default`, set the |factory|'s `[[DefaultPolicy]]` slot value to |policy|.
1.  Append |policyName| to |factory|'s `[[CreatedPolicyNames]]`.
1.  Return |policy|.

## <dfn abstract-op>Create a Trusted Type</dfn> ## {#create-a-trusted-type-algorithm}

Given a {{TrustedTypePolicy}} |policy|, a type name |trustedTypeName|,
a string |value| and a list |arguments|, execute the following steps:

1.  Let |functionName| be a function name for the given |trustedTypeName|,
    based on the following table:

    <table>
      <tr>
        <th>Function name</th>
        <th>Trusted Type name </th>
      </tr>
      <tr>
        <td>"createHTML"</td>
        <td>"TrustedHTML"</td>
      </tr>
      <tr>
        <td>"createScript"</td>
        <td>"TrustedScript"</td>
      </tr>
      <tr>
        <td>"createScriptURL"</td>
        <td>"TrustedScriptURL"</td>
      </tr>
    </table>

1.  Let |options| be the value of |policy|'s `[[options]]` slot.
1.  Let |function| be the value of the property in |options| named |functionName|.
1.  If |function| is `null`, throw a {{TypeError}}.
1.  Let |policyValue| be the result of invoking |function| with
    |value| as a first argument, items of |arguments| as subsequent arguments,
    and [[ECMASCRIPT#sec-method|callback **this** value]] set to `null`.
1.  If |policyValue| is an error, return |policyValue| and abort the following steps.
1.  If |policy|'s [=TrustedTypePolicy/name=] is `"default"` and the |policyValue|
    is null or undefined, return |policyValue|.

    Note: This is used in a [$Get Trusted Type compliant string$] algorithm to signal that
    a value was rejected.
1.  Let |dataString| be the result of stringifying |policyValue|.
1.  Let |trustedObject| be a new instance of an interface with a type
    name |trustedTypeName|, with its `[[Data]]` internal slot value
    set to |dataString|.
1.  Return |trustedObject|.

## <dfn abstract-op>Get Trusted Type compliant string</dfn> ## {#get-trusted-type-compliant-string-algorithm}

This algorithm will return a string that can be used with an
[=injection sink=], optionally unwrapping it from a matching [=Trusted Type=].
It will ensure that the Trusted Type [=enforcement=] rules were respected.

Given a {{TrustedType}} type (|expectedType|), a [=Realm/global object=] (|global|),
{{TrustedType}} or a string (|input|), a string (|sink|) and a string (|sinkGroup|), run these steps:

1.  Assert: |global| is a {{Window}}.

    Issue: Synchronize when TT are added to workers (perhaps use "has a CSP list"?)
1.  Let |cspList| be the |global|'s <a>CSP list</a>.
1.  If |cspList| does not contain a [[CSP3#content-security-policy-object|policy]]
    which <a>directive set</a> containing a [[CSP3#directives|directive]] with a name `"require-trusted-types-for"`,
    or that directive does not contain a <a>trusted-types-sink-group</a> which is a match for a value |sinkGroup|,
    return stringified |input| and abort these steps.
1.  If |input| has type |expectedType|, return stringified
    |input| and abort these steps.
1.  Let |convertedInput| be the result of executing [$Process value with a default policy$] with the same arguments as this algorithm.
1.  If the algorithm threw an error, rethrow the error and abort the following steps.
1.  If |convertedInput| is `null` or `undefined`, execute the following steps:
    1.  Let |disposition| be the result of executing [$Should sink type mismatch violation be blocked by Content Security Policy?$] algorithm,
        passing |global|, |input| as |source|, |sinkGroup| and |sink|.
    1.  If |disposition| is `“Allowed”`, return stringified |input| and abort futher steps.

        Note: This step assures that the default policy rejection will be reported, but ignored in a report-only mode.
    1. Throw a {{TypeError}} and abort further steps.
1. Assert: |convertedInput| has type |expectedType|.
1. Return stringified |convertedInput|.

## <dfn abstract-op>Process value with a default policy</dfn> ## {#process-value-with-a-default-policy-algorithm}

This algorithm routes a value to be assigned to an [=injection sink=]  through a default policy, should one exist.

Given a {{TrustedType}} type (|expectedType|), a [=Realm/global object=] (|global|),
{{TrustedType}} or a string (|input|), and a string (|sink|), run these steps:

1.  Let |defaultPolicy| be the value of |global|'s [=Window/trusted type policy factory=]'s `[[DefaultPolicy]]` slot. If the slot is empty, return `null`.
1.  Let |convertedInput| be the result of executing [$Create a
    Trusted Type$] algorithm, with the following arguments:
    *  |defaultPolicy| as |policy|
    *  |input| as |value|
    *  |expectedType|’s type name as |trustedTypeName|
    *  &laquo; |sink| &raquo; as |arguments|
1. If the algorithm threw an error, rethrow it. Otherwise, return |convertedInput|.

## <dfn abstract-op>Prepare the script URL and text</dfn> ## {#prepare-script-url-and-text}

Given a {{script}} (|script|), this algorithm performs the following steps:

1.  If |script| does not have a {{script/src}} content attribute, set its {{script/[[ScriptURL]]}} internal slot value to `null`.

1.  Otherwise, if |script|'s {{script/[[ScriptURL]]}} internal slot value is not equal to its {{script/src}} attribute value,
    set |script|'s {{script/[[ScriptURL]]}} to the result of executing [$Get Trusted Type compliant string$], with the following arguments:
      * {{TrustedScriptURL}} as |expectedType|,
      * |script|'s {{Document}}'s [=relevant global object=] as |global|,
      * |script|'s {{script/src}} attribute value as |input|,
      * `script.src` as |sink|,
      * `'script'` as |sinkGroup|.

    If the algorithm threw an error, rethrow the error and abort further steps.

1.  If |script|'s {{script/[[ScriptText]]}} internal slot value is not equal to its [=child text content=],
    set |script|'s {{script/[[ScriptText]]}} to the result of executing [$Get Trusted Type compliant string$], with the following arguments:
      * {{TrustedScriptURL}} as |expectedType|,
      * |script|'s {{Document}}'s [=relevant global object=] as |global|,
      * |script|'s [=child text content=] attribute value,
      * `script.text` as |sink|,
      * `'script'` as |sinkGroup|.

    If the algorithm threw an error, rethrow the error.

# Integrations # {#integrations}

<pre class="idl">
typedef (DOMString or TrustedHTML) HTMLString;
typedef (DOMString or TrustedScript) ScriptString;
typedef (USVString or TrustedScriptURL) ScriptURLString;
typedef (TrustedHTML or TrustedScript or TrustedScriptURL) TrustedType;

typedef (([TreatNullAs=EmptyString] DOMString) or TrustedHTML) HTMLStringDefaultsEmpty;
</pre>

Note: {{HTMLStringDefaultsEmpty}} is a non-nullable variant that accepts *null* on set.
Having this separate type allows [[webidl#TreatNullAs]] to attach to DOMString
per heycam/webidl#441.

Issue(w3c/webappsec-trusted-types#2): [[webidl#TreatNullAs|TreatNullAs=EmptyString]] is confusing.
See note "It should not be used in specifications unless ...".
For some sinks a `null` value will result in "", and "null" for others.
This already caused problems in the polyfill.

## Integration with HTML ## {#integration-with-html}

{{Window}} objects have a <dfn for="Window">trusted type policy factory</dfn>,
which is a {{TrustedTypePolicyFactory}} object.

Issue: Define for workers.

### Extensions to the Window interface ### {#extensions-to-the-window-interface}

This document extends the {{Window}} interface defined by [[HTML5|HTML]]:

<pre class="idl">
partial interface mixin Window {
  [Unforgeable] readonly attribute
      TrustedTypePolicyFactory trustedTypes;
};
</pre>

{{Window/trustedTypes}} returns the [[#integration-with-html|trusted
type policy factory]] of the current {{Window}}.

Note: The implementation in Chrome &lt; 78 uses `window.TrustedTypes` instead
      of `window.trustedTypes`.

Issue: Remove the note when the API in Chrome is shipped.

### Extensions to the Document interface ### {#extensions-to-the-document-interface}

This document modifies the {{Document}} interface defined by [[HTML5|HTML]]:

<pre class="idl">
partial interface mixin Document {
  [CEReactions] void write([TrustedTypes=TrustedHTML] HTMLString... text);
  [CEReactions] void writeln([TrustedTypes=TrustedHTML] HTMLString... text);
};
</pre>

### Enforcement for scripts ### {#enfocement-in-scripts}

#### Slots with trusted values

This document modifies {{script}} elements. Each script has:

: <dfn dfn-for="script">`[[ScriptURL]]`</dfn> internal slot.
::  A string, containing the URL to execute the script from
    that was set through a {{TrustedTypes}} compliant sink. Equivalent to
    {{HTMLScriptElement/src}} attribute value. Initially null.

: <dfn dfn-for="script">`[[ScriptText]]`</dfn> internal slot.
::  A string, containing the body of the script to execute that was set
    through a {{TrustedTypes}} compliant sink. Equivalent to script's
    [=child text content=]. Initially null.

#### Setting slot values

This document modifies how {{HTMLScriptElement}} [=child text content=] can be set to allow applications to control dynamically created scripts. It does so by
adding the {{HTMLElement/innerText}} and {{Node/textContent}} attributes directly on {{HTMLScriptElement}}. The behavior of the attributes remains the same
as in their original counterparts, apart from additional behavior triggered by the {{TrustedTypes}} extended attribute presence.

Note: Using these IDL attributes is the recommended way of dynamically setting URL or a text of a script. Manipulating attribute nodes or text nodes directly will call a default policy on the final value when the script is prepared.

Issue: Figure out what to do with script.setAttribute('src'). See [DOM#789](https://github.com/whatwg/dom/issues/789).

<pre class="idl">
partial interface mixin HTMLScriptElement : HTMLElement {
 [CEReactions, TrustedTypes=TrustedScript] attribute [TreatNullAs=EmptyString] ScriptString innerText;
 [CEReactions, TrustedTypes=TrustedScript] attribute ScriptString? textContent;
 [CEReactions, TrustedTypes=TrustedScriptURL] attribute ScriptURLString src;
 [CEReactions, TrustedTypes=TrustedScript] attribute ScriptString text;
};
</pre>

On setting, the {{HTMLElement/innerText}}, {{Node/textContent}} and {{HTMLScriptElement/text}} IDL attributes perform the regular steps, and then set [=content object=]'s {{script/[[ScriptText]]}} internal slot value with the stringified value.

On setting, the {{HTMLScriptElement/src}} IDL attribute performs the usual steps, and then sets [=content object=]'s {{script/[[ScriptURL]]}} internal slot value to its {{script/src}} content attribute value.

#### Slot value verification

The [=prepare a script=] algorithm is modified as follows:

<ol><li>

    <p>If the <code id="script-processing-model:the-script-element-18"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element is marked as having <a href="https://html.spec.whatwg.org/#already-started" id="script-processing-model:already-started">"already started"</a>, then
    return. The script is not executed.</p>

   </li><li>

    <p>If the element has its <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-3">"parser-inserted"</a> flag set, then set <var>was-parser-inserted</var> to true and unset the element's
    <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-4">"parser-inserted"</a> flag. Otherwise, set <var>was-parser-inserted</var> to
    false.</p>

    <p class="note">This is done so that if parser-inserted <code id="script-processing-model:the-script-element-19"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> elements fail to run
    when the parser tries to run them, e.g. because they are empty or specify an unsupported
    scripting language, another script can later mutate them and cause them to run again.</p>



   </li><li>

    <p>If <var>was-parser-inserted</var> is true and the element does not have an <code id="script-processing-model:attr-script-async-2"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code> attribute, then set the element's
    <a href="https://html.spec.whatwg.org/#non-blocking" id="script-processing-model:non-blocking-3">"non-blocking"</a> flag to true.</p>

    <p class="note">This is done so that if a parser-inserted <code id="script-processing-model:the-script-element-20"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element fails to
    run when the parser tries to run it, but it is later executed after a script dynamically updates
    it, it will execute in a non-blocking fashion even if the <code id="script-processing-model:attr-script-async-3"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code>
    attribute isn't set.</p>

   </li><li><ins>Execute the [$Prepare the script URL and text$] algorithm upon the {{script}} element. If that algorithm threw an error, then return. The script is not executed.

   </li><li><p>Let <var>source text</var> be the element's <del><a id="script-processing-model:child-text-content" href="https://dom.spec.whatwg.org/#concept-child-text-content" data-x-internal="child-text-content">child text content</a></del> <ins>`[[ScriptText]]` internal slot value</ins>.</p>

   </li><li><ins><p>Let <var>src</var> be the element's `[[ScriptURL]]` internal slot value</ins>.</p>

   </li><li id="script-processing-empty">

    <p>If <del>the element has no <code id="script-processing-model:attr-script-src-3"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute</del> <ins>|src| is null</ins>, and <var>source
    text</var> is the empty string, then return. The script is not executed.</p>

   </li><li><p>If the element is not <a id="script-processing-model:connected-3" href="https://dom.spec.whatwg.org/#connected" data-x-internal="connected">connected</a>, then return. The script is not
   executed.</p></li><li id="script-processing-prepare">

    <p>If either:</p>

    <ul class="brief"><li>the <code id="script-processing-model:the-script-element-21"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has a <code id="script-processing-model:attr-script-type-2"><a href="https://html.spec.whatwg.org/#attr-script-type">type</a></code> attribute
     and its value is the empty string, or</li><li>the <code id="script-processing-model:the-script-element-22"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has no <code id="script-processing-model:attr-script-type-3"><a href="https://html.spec.whatwg.org/#attr-script-type">type</a></code> attribute
     but it has a <code id="script-processing-model:attr-script-language"><a href="https://html.spec.whatwg.org/#attr-script-language">language</a></code> attribute and <em>that</em>
     attribute's value is the empty string, or</li><li>the <code id="script-processing-model:the-script-element-23"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has neither a <code id="script-processing-model:attr-script-type-4"><a href="https://html.spec.whatwg.org/#attr-script-type">type</a></code>
     attribute nor a <code id="script-processing-model:attr-script-language-2"><a href="https://html.spec.whatwg.org/#attr-script-language">language</a></code> attribute, then</li></ul>

    <p>...let <var>the script block's type string</var> for this <code id="script-processing-model:the-script-element-24"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element be
    "<code>text/javascript</code>".</p>

    <p>Otherwise, if the <code id="script-processing-model:the-script-element-25"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has a <code id="script-processing-model:attr-script-type-5"><a href="https://html.spec.whatwg.org/#attr-script-type">type</a></code> attribute, let <var>the script block's type string</var>
    for this <code id="script-processing-model:the-script-element-26"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element be the value of that attribute with <a href="https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace" id="script-processing-model:strip-leading-and-trailing-ascii-whitespace" data-x-internal="strip-leading-and-trailing-ascii-whitespace">leading and trailing ASCII whitespace
    stripped</a>.</p>

    <p>Otherwise, the element has a non-empty <code id="script-processing-model:attr-script-language-3"><a href="https://html.spec.whatwg.org/#attr-script-language">language</a></code>
    attribute; let <var>the script block's type string</var> for this <code id="script-processing-model:the-script-element-27"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element
    be the concatenation of the string "<code>text/</code>" followed by the value of the
    <code id="script-processing-model:attr-script-language-4"><a href="https://html.spec.whatwg.org/#attr-script-language">language</a></code> attribute.</p>


    <p class="note">The <code id="script-processing-model:attr-script-language-5"><a href="https://html.spec.whatwg.org/#attr-script-language">language</a></code> attribute is never
    conforming, and is always ignored if there is a <code id="script-processing-model:attr-script-type-6"><a href="https://html.spec.whatwg.org/#attr-script-type">type</a></code>
    attribute present.</p>

    <p>Determine <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type">the script's type</a> as follows:</p>

    <ul><li>If <var>the script block's type string</var> is a <a id="script-processing-model:javascript-mime-type-essence-match" href="https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match" data-x-internal="javascript-mime-type-essence-match">JavaScript MIME type essence
     match</a>, <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-2">the script's type</a> is "<code>classic</code>".</li><li>If <var>the script block's type string</var> is an <a id="script-processing-model:ascii-case-insensitive" href="https://infra.spec.whatwg.org/#ascii-case-insensitive" data-x-internal="ascii-case-insensitive">ASCII case-insensitive</a>
     match for the string "<code>module</code>", <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-3">the
     script's type</a> is "<code>module</code>".</li><li>If neither of the above conditions are true, then return. No script is executed.</li></ul>

   </li><li>

    <p>If <var>was-parser-inserted</var> is true, then flag the element as
    <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-5">"parser-inserted"</a> again, and set the element's <a href="https://html.spec.whatwg.org/#non-blocking" id="script-processing-model:non-blocking-4">"non-blocking"</a> flag to
    false.</p>

   </li><li id="script-processing-start">

    <p>Set the element's <a href="https://html.spec.whatwg.org/#already-started" id="script-processing-model:already-started-2">"already started"</a> flag.</p>

   </li><li>

    <p>If the element is flagged as <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-6">"parser-inserted"</a>, but the element's
    <a id="script-processing-model:node-document-2" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node document</a> is not the <code id="script-processing-model:document"><a href="https://html.spec.whatwg.org/#document">Document</a></code> of the parser that created the
    element, then return.</p>

   </li><li id="script-processing-noscript">

    <p>If <a href="https://html.spec.whatwg.org/#concept-n-noscript" id="script-processing-model:concept-n-noscript">scripting is disabled</a> for the <code id="script-processing-model:the-script-element-28"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code>
    element, then return. The script is not executed.</p>

    <p class="note">The definition of <a href="https://html.spec.whatwg.org/#concept-n-noscript" id="script-processing-model:concept-n-noscript-2">scripting is disabled</a>
    means that, amongst others, the following scripts will not execute: scripts in
    <code id="script-processing-model:xmlhttprequest"><a data-x-internal="xmlhttprequest" href="https://xhr.spec.whatwg.org/#xmlhttprequest">XMLHttpRequest</a></code>'s <code id="script-processing-model:dom-xmlhttprequest-responsexml"><a data-x-internal="dom-xmlhttprequest-responsexml" href="https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsexml">responseXML</a></code>
    documents, scripts in <code id="script-processing-model:domparser"><a data-x-internal="domparser" href="https://w3c.github.io/DOM-Parsing/#the-domparser-interface">DOMParser</a></code>-created documents, scripts in documents created by
    <code id="script-processing-model:xsltprocessor"><a href="https://html.spec.whatwg.org/#xsltprocessor">XSLTProcessor</a></code>'s <code id="script-processing-model:dom-xsltprocessor-transformtodocument"><a href="https://html.spec.whatwg.org/#dom-xsltprocessor-transformtodocument">transformToDocument</a></code> feature, and scripts
    that are first inserted by a script into a <code id="script-processing-model:document-2"><a href="https://html.spec.whatwg.org/#document">Document</a></code> that was created using the
    <code id="script-processing-model:dom-domimplementation-createdocument"><a data-x-internal="dom-domimplementation-createdocument" href="https://dom.spec.whatwg.org/#dom-domimplementation-createdocument">createDocument()</a></code> API. <a href="https://html.spec.whatwg.org/#refsXHR">\[XHR\]</a>
    <a href="https://html.spec.whatwg.org/#refsDOMPARSING">\[DOMPARSING\]</a> <a href="https://html.spec.whatwg.org/#refsXSLTP">\[XSLTP\]</a> <a href="https://html.spec.whatwg.org/#refsDOM">\[DOM\]</a></p>


   </li><li>

   <p>If the <code id="script-processing-model:the-script-element-29"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has a <code id="script-processing-model:attr-script-nomodule"><a href="https://html.spec.whatwg.org/#attr-script-nomodule">nomodule</a></code>
   content attribute and <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-4">the script's type</a> is "<code>classic</code>", then return. The script is not executed.</p>

   <p class="note">This means specifying <code id="script-processing-model:attr-script-nomodule-2"><a href="https://html.spec.whatwg.org/#attr-script-nomodule">nomodule</a></code> on a
   <a href="https://html.spec.whatwg.org/#module-script" id="script-processing-model:module-script">module script</a> has no effect; the algorithm continues onward.</p>

   </li><li id="script-processing-csp"><p>If <del>the <code id="script-processing-model:the-script-element-30"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element does not have a <code id="script-processing-model:attr-script-src-4"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> content attribute</del><ins>|src| is null</ins>, and the <a id="script-processing-model:should-element's-inline-behavior-be-blocked-by-content-security-policy" href="https://w3c.github.io/webappsec-csp/#should-block-inline" data-x-internal="should-element's-inline-behavior-be-blocked-by-content-security-policy">Should element's inline
   behavior be blocked by Content Security Policy?</a> algorithm returns "<code>Blocked</code>" when executed upon the <code id="script-processing-model:the-script-element-31"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element, "<code>script</code>", and <var>source text</var>, then return. The script is not executed.
   <a href="https://html.spec.whatwg.org/#refsCSP">\[CSP\]</a></p></li><li id="script-processing-for">

    <p>If the <code id="script-processing-model:the-script-element-32"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has an <code id="script-processing-model:attr-script-event"><a href="https://html.spec.whatwg.org/#attr-script-event">event</a></code>
    attribute and a <code id="script-processing-model:attr-script-for"><a href="https://html.spec.whatwg.org/#attr-script-for">for</a></code> attribute, and <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-5">the script's type</a> is "<code>classic</code>",
    then:</p>

    <ol><li><p>Let <var>for</var> be the value of the <code id="script-processing-model:attr-script-for-2"><a href="https://html.spec.whatwg.org/#attr-script-for">for</a></code>
     attribute.</p></li><li><p>Let <var>event</var> be the value of the <code id="script-processing-model:attr-script-event-2"><a href="https://html.spec.whatwg.org/#attr-script-event">event</a></code> attribute.</p></li><li><p><a id="script-processing-model:strip-leading-and-trailing-ascii-whitespace-2" href="https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace" data-x-internal="strip-leading-and-trailing-ascii-whitespace">Strip leading and trailing ASCII whitespace</a> from <var>event</var> and
     <var>for</var>.</p></li><li><p>If <var>for</var> is not an <a id="script-processing-model:ascii-case-insensitive-2" href="https://infra.spec.whatwg.org/#ascii-case-insensitive" data-x-internal="ascii-case-insensitive">ASCII case-insensitive</a> match for the
     string "<code>window</code>", then return. The script is not executed.</p></li><li><p>If <var>event</var> is not an <a id="script-processing-model:ascii-case-insensitive-3" href="https://infra.spec.whatwg.org/#ascii-case-insensitive" data-x-internal="ascii-case-insensitive">ASCII case-insensitive</a> match for
     either the string "<code>onload</code>" or the string "<code>onload()</code>", then return. The script is not executed.</p></li></ol>

   </li><li id="script-processing-encoding">

    <p>If the <code id="script-processing-model:the-script-element-33"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has a <code id="script-processing-model:attr-script-charset"><a href="https://html.spec.whatwg.org/#attr-script-charset">charset</a></code>
    attribute, then let <var>encoding</var> be the result of <a id="script-processing-model:getting-an-encoding" href="https://encoding.spec.whatwg.org/#concept-encoding-get" data-x-internal="getting-an-encoding">getting an encoding</a> from
    the value of the <code id="script-processing-model:attr-script-charset-2"><a href="https://html.spec.whatwg.org/#attr-script-charset">charset</a></code> attribute.</p>

    <p>If the <code id="script-processing-model:the-script-element-34"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element does not have a <code id="script-processing-model:attr-script-charset-3"><a href="https://html.spec.whatwg.org/#attr-script-charset">charset</a></code> attribute, or if <a id="script-processing-model:getting-an-encoding-2" href="https://encoding.spec.whatwg.org/#concept-encoding-get" data-x-internal="getting-an-encoding">getting an encoding</a>
    failed, let <var>encoding</var> be the same as <a href="https://dom.spec.whatwg.org/#concept-document-encoding" id="script-processing-model:document's-character-encoding" data-x-internal="document's-character-encoding">the
    encoding</a> of the <code id="script-processing-model:the-script-element-35"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element's <a id="script-processing-model:node-document-3" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node document</a>.</p>

    <p class="note">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-6">the script's type</a> is "<code>module</code>", this encoding will be ignored.</p>

   </li><li><p>Let <var>classic script CORS setting</var> be the current state of the element's <code id="script-processing-model:attr-script-crossorigin"><a href="https://html.spec.whatwg.org/#attr-script-crossorigin">crossorigin</a></code> content attribute.</p></li><li><p>Let <var>module script credentials mode</var> be the <a href="https://html.spec.whatwg.org/#module-script-credentials-mode" id="script-processing-model:module-script-credentials-mode">module script credentials
   mode</a> for the element's <code id="script-processing-model:attr-script-crossorigin-2"><a href="https://html.spec.whatwg.org/#attr-script-crossorigin">crossorigin</a></code> content
   attribute.</p>

   </li><li><p>Let <var>cryptographic nonce</var> be the element's <a href="https://html.spec.whatwg.org/#cryptographicnonce" id="script-processing-model:cryptographicnonce">\[\[CryptographicNonce\]\]</a>
   internal slot's value.</p></li><li>

    <p>If the <code id="script-processing-model:the-script-element-36"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has an <code id="script-processing-model:attr-script-integrity"><a href="https://html.spec.whatwg.org/#attr-script-integrity">integrity</a></code> attribute, then let <var>integrity
    metadata</var> be that attribute's value.</p>

    <p>Otherwise, let <var>integrity metadata</var> be the empty string.</p>

   </li><li><p>Let <var>referrer policy</var> be the current state of the element's <code id="script-processing-model:attr-script-referrerpolicy"><a href="https://html.spec.whatwg.org/#attr-script-referrerpolicy">referrerpolicy</a></code> content attribute.</p></li><li><p>Let <var>parser metadata</var> be "<code>parser-inserted</code>" if the
   <code id="script-processing-model:the-script-element-37"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element has been flagged as <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-7">"parser-inserted"</a>, and
   "<code>not-parser-inserted</code>" otherwise.</p></li><li><p>Let <var>options</var> be a <a href="https://html.spec.whatwg.org/#script-fetch-options" id="script-processing-model:script-fetch-options">script fetch options</a> whose <a href="https://html.spec.whatwg.org/#concept-script-fetch-options-nonce" id="script-processing-model:concept-script-fetch-options-nonce">cryptographic nonce</a> is <var>cryptographic
   nonce</var>, <a href="https://html.spec.whatwg.org/#concept-script-fetch-options-integrity" id="script-processing-model:concept-script-fetch-options-integrity">integrity metadata</a> is
   <var>integrity metadata</var>, <a href="https://html.spec.whatwg.org/#concept-script-fetch-options-parser" id="script-processing-model:concept-script-fetch-options-parser">parser
   metadata</a> is <var>parser metadata</var>, <a href="https://html.spec.whatwg.org/#concept-script-fetch-options-credentials" id="script-processing-model:concept-script-fetch-options-credentials">credentials mode</a> is <var>module script
   credentials mode</var>, and <a href="https://html.spec.whatwg.org/#concept-script-fetch-options-referrer-policy" id="script-processing-model:concept-script-fetch-options-referrer-policy">referrer
   policy</a> is <var>referrer policy</var>.</p></li><li><p>Let <var>settings object</var> be the element's <a id="script-processing-model:node-document-4" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node document</a>'s
   <a href="https://html.spec.whatwg.org/#relevant-settings-object" id="script-processing-model:relevant-settings-object">relevant settings object</a>.</p></li><li id="script-processing-src-prepare">

    <p>If <del>the element has a <code id="script-processing-model:attr-script-src-5"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> content attribute</del><ins>|src| is not null</ins>, then:</p>

    <ol><li><del><p>Let <var>src</var> be the value of the element's <code id="script-processing-model:attr-script-src-6"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute.</p></del></li><li><p>If <var>src</var> is the empty string, <a href="https://html.spec.whatwg.org/#queue-a-task" id="script-processing-model:queue-a-task">queue a task</a> to <a href="https://dom.spec.whatwg.org/#concept-event-fire" id="script-processing-model:concept-event-fire" data-x-internal="concept-event-fire">fire an event</a> named <code id="script-processing-model:event-error"><a href="https://html.spec.whatwg.org/#event-error">error</a></code>
     at the element, and return.</p></li><li><p>Set the element's <a href="https://html.spec.whatwg.org/#concept-script-external" id="script-processing-model:concept-script-external">from an external file</a>
     flag.</p></li><li><p><a href="https://html.spec.whatwg.org/#parse-a-url" id="script-processing-model:parse-a-url">Parse</a> <var>src</var> relative to the element's
     <a id="script-processing-model:node-document-5" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node document</a>.</p></li><li><p>If the previous step failed, <a href="https://html.spec.whatwg.org/#queue-a-task" id="script-processing-model:queue-a-task-2">queue a task</a> to <a href="https://dom.spec.whatwg.org/#concept-event-fire" id="script-processing-model:concept-event-fire-2" data-x-internal="concept-event-fire">fire an event</a> named <code id="script-processing-model:event-error-2"><a href="https://html.spec.whatwg.org/#event-error">error</a></code>
     at the element, and return. Otherwise, let <var>url</var> be the <a href="https://html.spec.whatwg.org/#resulting-url-record" id="script-processing-model:resulting-url-record">resulting URL
     record</a>.</p></li><li>
      <p>Switch on <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-7">the script's type</a>:</p>

      <dl class="switch"><dt>"<code>classic</code>"</dt><dd>
        <p><a href="https://html.spec.whatwg.org/#fetch-a-classic-script" id="script-processing-model:fetch-a-classic-script">Fetch a classic script</a> given <var>url</var>, <var>settings object</var>,
        <var>options</var>, <var>classic script CORS setting</var>, and <var>encoding</var>.</p>
       </dd><dt>"<code>module</code>"</dt><dd>
        <p><a href="https://html.spec.whatwg.org/#fetch-a-module-script-tree" id="script-processing-model:fetch-a-module-script-tree">Fetch an external module script graph</a> given <var>url</var>, <var>settings
        object</var>, and <var>options</var>.</p>
       </dd></dl>

      <p>When the chosen algorithm asynchronously completes, set <a href="https://html.spec.whatwg.org/#concept-script-script" id="script-processing-model:concept-script-script">the script's script</a> to the result. At that time,
      <a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-2">the script is ready</a>.</p>

      <p>For performance reasons, user agents may start fetching the classic script or module graph
      (as defined above) as soon as the <code id="script-processing-model:attr-script-src-7"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute is set,
      instead, in the hope that the element will be inserted into the document (and that the <code id="script-processing-model:attr-script-crossorigin-3"><a href="https://html.spec.whatwg.org/#attr-script-crossorigin">crossorigin</a></code> attribute won't change value in the
      meantime). Either way, once the element is <a href="https://html.spec.whatwg.org/#insert-an-element-into-a-document" id="script-processing-model:insert-an-element-into-a-document">inserted into the document</a>, the load must have started as described in this
      step. If the UA performs such prefetching, but the element is never inserted in the document,
      or the <code id="script-processing-model:attr-script-src-8"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute is dynamically changed, or the <code id="script-processing-model:attr-script-crossorigin-4"><a href="https://html.spec.whatwg.org/#attr-script-crossorigin">crossorigin</a></code> attribute is dynamically changed, then the
      user agent will not execute the script so obtained, and the fetching process will have been
      effectively wasted.</p>

     </li></ol>

   </li><li id="establish-script-block-source">

    <p>If <del>the element does not have a <code id="script-processing-model:attr-script-src-9"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> content attribute</del><ins>|src| is null</ins>,
    run these substeps:</p>

    <ol><li><p>Let <var>base URL</var> be the <code id="script-processing-model:the-script-element-38"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element's <a id="script-processing-model:node-document-6" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node
     document</a>'s <a href="https://html.spec.whatwg.org/#document-base-url" id="script-processing-model:document-base-url">document base URL</a>.</p></li><li>
      <p>Switch on <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-8">the script's type</a>:</p>

      <dl class="switch"><dt>"<code>classic</code>"</dt><dd>
        <ol><li><p>Let <var>script</var> be the result of <a href="https://html.spec.whatwg.org/#creating-a-classic-script" id="script-processing-model:creating-a-classic-script">creating a classic script</a> using
         <var>source text</var>, <var>settings object</var>, <var>base URL</var>, and
         <var>options</var>.</p></li><li><p>Set <a href="https://html.spec.whatwg.org/#concept-script-script" id="script-processing-model:concept-script-script-2">the script's script</a> to
         <var>script</var>.</p></li><li><p><a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-3">The script is ready</a>.</p></li></ol>
       </dd><dt>"<code>module</code>"</dt><dd>
        <ol><li><p><a href="https://html.spec.whatwg.org/#fetch-an-inline-module-script-graph" id="script-processing-model:fetch-an-inline-module-script-graph">Fetch an inline module script graph</a>, given <var>source text</var>,
         <var>base URL</var>, <var>settings object</var>, and <var>options</var>. When this
         asynchronously completes, set <a href="https://html.spec.whatwg.org/#concept-script-script" id="script-processing-model:concept-script-script-3">the script's
         script</a> to the result. At that time, <a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-4">the script is ready</a>.</p></li></ol>
       </dd></dl>
     </li></ol>
   </li><li>

    <p>Then, follow the first of the following options that describes the situation:</p>

    <dl class="switch"><dt id="script-processing-defer">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-9">the script's
     type</a> is "<code>classic</code>", and the element has a <code id="script-processing-model:attr-script-src-10"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute, and the element has a <code id="script-processing-model:attr-script-defer"><a href="https://html.spec.whatwg.org/#attr-script-defer">defer</a></code> attribute, and the element has been flagged as
     <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-8">"parser-inserted"</a>, and the element does not have an <code id="script-processing-model:attr-script-async-4"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code> attribute</dt><dt id="script-processing-module-noasync-parser-inserted">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-10">the script's type</a> is "<code>module</code>", and
     the element has been flagged as <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-9">"parser-inserted"</a>, and the element does not have
     an <code id="script-processing-model:attr-script-async-5"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code> attribute</dt><dd>

      <p>Add the element to the end of the <dfn id="list-of-scripts-that-will-execute-when-the-document-has-finished-parsing">list of scripts that will execute when the document
      has finished parsing</dfn> associated with the <code id="script-processing-model:document-3"><a href="https://html.spec.whatwg.org/#document">Document</a></code> of the parser that
      created the element.</p>

      <p>When <a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-5">the script is ready</a>, set the element's <a href="https://html.spec.whatwg.org/#ready-to-be-parser-executed" id="script-processing-model:ready-to-be-parser-executed">"ready to be
      parser-executed"</a> flag. The parser will handle executing the script.</p>

     </dd><dt id="script-processing-parser-inserted">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-11">the script's
     type</a> is "<code>classic</code>", and the element has a <code id="script-processing-model:attr-script-src-11"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute, and the element has been flagged as
     <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-10">"parser-inserted"</a>, and the element does not have an <code id="script-processing-model:attr-script-async-6"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code> attribute</dt><dd>

      <p>The element is the <a href="https://html.spec.whatwg.org/#pending-parsing-blocking-script" id="script-processing-model:pending-parsing-blocking-script">pending parsing-blocking script</a> of the
      <code id="script-processing-model:document-4"><a href="https://html.spec.whatwg.org/#document">Document</a></code> of the parser that created the element. (There can only be one such
      script per <code id="script-processing-model:document-5"><a href="https://html.spec.whatwg.org/#document">Document</a></code> at a time.)</p>

      <p>When <a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-6">the script is ready</a>, set the element's <a href="https://html.spec.whatwg.org/#ready-to-be-parser-executed" id="script-processing-model:ready-to-be-parser-executed-2">"ready to be
      parser-executed"</a> flag. The parser will handle executing the script.</p>

     </dd><dt id="script-processing-src-sync">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-12">the script's
     type</a> is "<code>classic</code>", and the element has a <code id="script-processing-model:attr-script-src-12"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute, and the element does not have an <code id="script-processing-model:attr-script-async-7"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code> attribute, and the element does not have the
     <a href="https://html.spec.whatwg.org/#non-blocking" id="script-processing-model:non-blocking-5">"non-blocking"</a> flag set</dt><dt id="script-processing-module-noasync">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-13">the script's
     type</a> is "<code>module</code>", and the element does not have an <code id="script-processing-model:attr-script-async-8"><a href="https://html.spec.whatwg.org/#attr-script-async">async</a></code> attribute, and the element does not have the
     <a href="https://html.spec.whatwg.org/#non-blocking" id="script-processing-model:non-blocking-6">"non-blocking"</a> flag set</dt><dd>

      <p>Add the element to the end of the <dfn id="list-of-scripts-that-will-execute-in-order-as-soon-as-possible">list of scripts that will execute in order as soon
      as possible</dfn> associated with the <a id="script-processing-model:node-document-7" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node document</a> of the <code id="script-processing-model:the-script-element-39"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code>
      element at the time the <a href="https://html.spec.whatwg.org/#prepare-a-script" id="script-processing-model:prepare-a-script-5">prepare a script</a> algorithm started.</p>

      <p>When <a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-7">the script is ready</a>, run the following steps:</p>

      <ol><li><p>If the element is not now the first element in the <a href="https://html.spec.whatwg.org/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible" id="script-processing-model:list-of-scripts-that-will-execute-in-order-as-soon-as-possible">list of scripts that will
       execute in order as soon as possible</a> to which it was added above, then mark the
       element as ready but return without executing the script yet.</p></li><li><p><i>Execution</i>: <a href="https://html.spec.whatwg.org/#execute-the-script-block" id="script-processing-model:execute-the-script-block">Execute the script block</a> corresponding to the first
       script element in this <a href="https://html.spec.whatwg.org/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible" id="script-processing-model:list-of-scripts-that-will-execute-in-order-as-soon-as-possible-2">list of scripts that will execute in order as soon as
       possible</a>.</p></li><li><p>Remove the first element from this <a href="https://html.spec.whatwg.org/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible" id="script-processing-model:list-of-scripts-that-will-execute-in-order-as-soon-as-possible-3">list of scripts that will execute in order as
       soon as possible</a>.</p></li><li><p>If this <a href="https://html.spec.whatwg.org/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible" id="script-processing-model:list-of-scripts-that-will-execute-in-order-as-soon-as-possible-4">list of scripts that will execute in order as soon as possible</a> is
       still not empty and the first entry has already been marked as ready, then jump back to the
       step labeled <i>execution</i>.</p></li></ol>

     </dd><dt id="script-processing-src">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-14">the script's type</a>
     is "<code>classic</code>", and the element has a <code id="script-processing-model:attr-script-src-13"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute</dt><dt id="script-processing-module-async">If <a href="https://html.spec.whatwg.org/#concept-script-type" id="script-processing-model:concept-script-type-15">the script's
     type</a> is "<code>module</code>"</dt><dd>

      <p>The element must be added to the <dfn id="set-of-scripts-that-will-execute-as-soon-as-possible">set of scripts that will execute as soon as
      possible</dfn> of the <a id="script-processing-model:node-document-8" href="https://dom.spec.whatwg.org/#concept-node-document" data-x-internal="node-document">node document</a> of the <code id="script-processing-model:the-script-element-40"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element at the
      time the <a href="https://html.spec.whatwg.org/#prepare-a-script" id="script-processing-model:prepare-a-script-6">prepare a script</a> algorithm started.</p>

      <p>When <a href="https://html.spec.whatwg.org/#the-script-is-ready" id="script-processing-model:the-script-is-ready-8">the script is ready</a>, <a href="https://html.spec.whatwg.org/#execute-the-script-block" id="script-processing-model:execute-the-script-block-2">execute the script block</a> and then
      remove the element from the <a href="https://html.spec.whatwg.org/#set-of-scripts-that-will-execute-as-soon-as-possible" id="script-processing-model:set-of-scripts-that-will-execute-as-soon-as-possible">set of scripts that will execute as soon as
      possible</a>.</p>

     </dd><dt id="script-processing-style-delayed">If the element does not have a <code id="script-processing-model:attr-script-src-14"><a href="https://html.spec.whatwg.org/#attr-script-src">src</a></code> attribute, and the element has been flagged as
     <a href="https://html.spec.whatwg.org/#parser-inserted" id="script-processing-model:parser-inserted-11">"parser-inserted"</a>, and either the parser that created the <code id="script-processing-model:the-script-element-41"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> is
     an <a href="https://html.spec.whatwg.org/#xml-parser" id="script-processing-model:xml-parser-3">XML parser</a> or it's an <a href="https://html.spec.whatwg.org/#html-parser" id="script-processing-model:html-parser-3">HTML parser</a> whose <a href="https://html.spec.whatwg.org/#script-nesting-level" id="script-processing-model:script-nesting-level">script nesting
     level</a> is not greater than one, and the <code id="script-processing-model:document-6"><a href="https://html.spec.whatwg.org/#document">Document</a></code> of the <a href="https://html.spec.whatwg.org/#html-parser" id="script-processing-model:html-parser-4">HTML
     parser</a> or <a href="https://html.spec.whatwg.org/#xml-parser" id="script-processing-model:xml-parser-4">XML parser</a> that created the <code id="script-processing-model:the-script-element-42"><a href="https://html.spec.whatwg.org/#the-script-element">script</a></code> element <a href="https://html.spec.whatwg.org/#has-a-style-sheet-that-is-blocking-scripts" id="script-processing-model:has-a-style-sheet-that-is-blocking-scripts">has
     a style sheet that is blocking scripts</a></dt><dd>

      <p>The element is the <a href="https://html.spec.whatwg.org/#pending-parsing-blocking-script" id="script-processing-model:pending-parsing-blocking-script-2">pending parsing-blocking script</a> of the
      <code id="script-processing-model:document-7"><a href="https://html.spec.whatwg.org/#document">Document</a></code> of the parser that created the element. (There can only be one such
      script per <code id="script-processing-model:document-8"><a href="https://html.spec.whatwg.org/#document">Document</a></code> at a time.)</p>

      <p>Set the element's <a href="https://html.spec.whatwg.org/#ready-to-be-parser-executed" id="script-processing-model:ready-to-be-parser-executed-3">"ready to be parser-executed"</a> flag. The parser will handle
      executing the script.</p>

     </dd><dt id="script-processing-inline">Otherwise</dt><dd><a href="https://html.spec.whatwg.org/#immediately" id="script-processing-model:immediately-2">Immediately</a> <a href="https://html.spec.whatwg.org/#execute-the-script-block" id="script-processing-model:execute-the-script-block-3">execute the script block</a>, even if other scripts are
     already executing.</dd></dl>

   </li></ol>

### Enforcement in element attributes ### {#enforcement-in-sinks}

This document modifies following IDL attributes of various DOM elements:

<pre class="idl">
partial interface mixin HTMLIFrameElement : HTMLElement {
  [CEReactions, TrustedTypes=TrustedHTML] attribute HTMLString srcdoc;
};

partial interface HTMLEmbedElement : HTMLElement {
  [CEReactions, TrustedTypes=TrustedScriptURL] attribute ScriptURLString src;
};

partial interface HTMLObjectElement : HTMLElement {
  [CEReactions, TrustedTypes=TrustedScriptURL] attribute ScriptURLString data;
  [CEReactions, TrustedTypes=TrustedScriptURL] attribute DOMString codeBase; // obsolete
};
</pre>

Issue: Add base.href enforcement.

### Enforcement in timer functions ### {#enforcement-in-timer-functions}

This document modifies the {{WindowOrWorkerGlobalScope}} interface mixin:

<pre class="idl">
typedef (ScriptString or Function) TrustedTimerHandler;

partial interface mixin WindowOrWorkerGlobalScope {
  long setTimeout(TrustedTimerHandler handler, optional long timeout = 0, any... arguments);
  long setInterval(TrustedTimerHandler handler, optional long timeout = 0, any... arguments);
};
</pre>

To the [[HTML5#timer-initialisation-steps|timer initialization steps algorithm]],
add this step between 7.1 and 7.2:

1.  If the first operation argument is not a {{Function}}, or if the first operation argument is a {{TrustedType}}, set the first operation argument to the result of executing
    the [$Get Trusted Type compliant string$] algorithm, with
    *   |global| set to the [=context object=]'s [=relevant global object=].
    *   |input| set to the first method argument, and
    *   |expectedType| set to {{TrustedScript}}.
    *   |sink| set to `Window.setInterval` if <var ignore>repeat</var> is true, `Window.setTimeout` otherwise.
    *   |sinkGroup| set to `'script'`.

        Note: This matches the logic that the extended attribute would apply.

Note: This makes sure that a {{TrustedScript}} is passed to timer
functions in place of a string when Trusted Types are enforced, but
also unconditionally accepts any {{Function}} object.

### Enforcement in event handler content attributes ### {#enforcement-in-event-handler-content-attributes}

This document modifies the
[=attribute change steps=] for an [[HTML5#event-handler-content-attributes|event handler content attribute]].

At the beginning of step 5, insert the following steps:

1.  Let |value| be the result of executing the
    [$Get Trusted Type compliant string$] algorithm, with the following arguments:
    *   |value| as |input|,
    *   {{TrustedScript}} as |expectedType|,
    *   `'script'` as |sinkGroup|
    *   |sink| being the result of [=concatenating=] the list &laquo; <var ignore>element</var>'s [=Element/local name=], |localName| &raquo; with `"."` as a |separator|.

        Note: For example, `document.createElement('div').onclick = value` will result in |sink| being `'div.onclick'`.

    *   <var ignore>eventTarget</var>'s [=relevant global object=] as |global|,

1.  If the algorithm throws an error, abort these steps.

Note: This also applies to events in [[SVG2#EventAttributes]].

<div class="example" id="event-handlers-example">
  <pre highlight=js>
  // Content-Security-Policy: require-trusted-types-for 'script'

  const img = document.createElement('img');
  img.setAttribute('onerror', 'alert(1)'); // TypeError
  </pre>
</div>

## Integration with SVG ## {#integration-with-svg}

This document modifies the {{SVGScriptElement}} interface to enforce Trusted Types:

<pre class="idl">
partial interface mixin SVGScriptElement : SVGElement {
 // overwrites the definition in SVGURIReference.
 [TrustedTypes=TrustedScriptURL] readonly attribute ScriptURLString href;
};
</pre>

## Integration with DOM ## {#integration-with-dom}

This document modifies the {{Element}} interface, adding <a>attribute validation steps</a>:

<p><ins>This and <a lt="other applicable specifications">other specifications</a> may define
<dfn export id=concept-element-attributes-validation-ext>attribute validation steps</dfn> for
<a for=/>elements</a>. The algorithm is passed <var>element</var>, <var>localName</var>,
<var>value</var>, and <var>namespace</var>.</ins>

This document changes the  <a>handle attribute changes</a> algorithm, adding the following step at the beginning:
<ol>
 <li><ins><p>Run the <a>attribute validation steps</a> with <var>element</var>,
 <var>attribute</var>'s <a for=Attr>local name</a>, <var>newValue</var> and
 <var>attribute</var>'s <a for=Attr>namespace</a>. If this throws an exception, then
 rethrow the exception and abort further steps.</ins>
</ol>

Additionally, this document changes the <a spec=dom>append</a> an attribute algorithm:

<p>To <dfn export id=concept-element-attributes-append lt="append an attribute">append</dfn> an
<a>attribute</a> <var>attribute</var> to an <a for="/">element</a> <var>element</var>
<ins>with a <var>value</var></ins>, run these steps:

<ol>
 <li><p><a>Handle attribute changes</a> for <var>attribute</var> with <var>element</var>, null, and
 <del><var>attribute</var>'s <a for=Attr>value</a></del><ins><var>value</var></ins>.

 <li><ins><p>Set <var>attribute</var>'s <a for=Attr>value</a> to <var>value</var>.</ins>

 <li><p><a for=list>Append</a> <var>attribute</var> to <var>element</var>'s
 <a for=Element>attribute list</a>.
 <li><p>Set <var>attribute</var>'s <a for=Attr>element</a> to <var>element</var>.
</ol>

Callers of this algorithm are changed accordingly.

Issue: Remove when <a href="https://github.com/whatwg/dom/pull/809">DOM #809</a> is merged.


## Integration with DOM Parsing ## {#integration-with-dom-parsing}

This document modifies the following interfaces defined by [[DOM-Parsing]]:

<pre class="idl">
partial interface Element {
  [CEReactions, TrustedTypes=TrustedHTML] attribute HTMLStringDefaultsEmpty outerHTML;
  [CEReactions] void insertAdjacentHTML(DOMString position, [TrustedTypes=TrustedHTML] HTMLString text);
};

partial interface mixin InnerHTML { // specified in a draft version at https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin
  [CEReactions, TrustedTypes=TrustedHTML] attribute HTMLStringDefaultsEmpty innerHTML;
};

partial interface Range {
  [CEReactions, NewObject] DocumentFragment createContextualFragment([TrustedTypes=TrustedHTML] HTMLString fragment);
};

[Constructor, Exposed=Window]
interface DOMParser {
  [NewObject] Document parseFromString([TrustedTypes=TrustedHTML] HTMLString str, SupportedType type);
};
</pre>

## Integration with Content Security Policy ## {#integration-with-content-security-policy}

### <dfn lt="require-trusted-types-for-directive">require-trusted-types-for</dfn> directive ### {#require-trusted-types-for-csp-directive}

This document defines *require-trusted-types-for* - a new [[CSP3#directives|Content Security Policy directive]].

{{#require-trusted-types-for-directive|require-trusted-types-for}} directive configures the Trusted
Types framework for all the [=injection sinks=] of certain groups in a current [=Realm|realm=].
Specifically, it defines what should be the behavior when a string value is passed to an [=injection sink=]
of a given group (i.e. should the type-based enforcement be enabled for such sinks).

Note: Currently, only the enforcement for [[#dom-xss-injection-sinks]] is specified.

The syntax for the directive's [=directive/name=] and [=directive/value=] is described by the following
ABNF:

<pre>
directive-name = "require-trusted-types-for"
directive-value = <a>trusted-types-sink-group</a> *( <a href="https://w3c.github.io/webappsec-csp/#grammardef-required-ascii-whitespace">required-ascii-whitespace</a> <a>trusted-types-sink-group</a>)
<dfn>trusted-types-sink-group</dfn> = "'script'"
</pre>

<div class="example" id="require-tt-for-script-header">
Enforce Trusted Types at the DOM XSS injection sinks.

<pre class="http">
Content-Security-Policy: require-trusted-types-for 'script'
</pre>
</div>

#### `require-trusted-types-for` Pre-Navigation check #### {#require-trusted-types-for-pre-navigation-check}

Given a [[Fetch#concept-request|request]] (|request|), a string |navigation type| and a [[CSP3#content-security-policy-object|policy]] (|policy|), this algorithm returns `"Blocked"`
if a navigation violates the {{#require-trusted-types-for-directive|require-trusted-types-for}} directive's constraints and `"Allowed"`
otherwise. This constitutes the {{#require-trusted-types-for-directive|require-trusted-types-for}} directive's [=pre-navigation check=]:

Note: This algorithm assures that the code to be executed by a navigation to a `javascript:` URL will have to pass through a
<a>default policy</a>'s `createScript` function, in addition to all other restrictions imposed by other CSP directives.

1. If |request|'s [=request/url=]'s [=url/scheme=] is not `"javascript"`, return `"Allowed"` and abort further steps.
1. Let |urlString| be the result of running the [=URL serializer=] on |request|'s [=request/url=].
1. Let |encodedScriptSource| be the result of removing the leading `"javascript:"` from |urlString|.
1. Let |convertedScriptSource| be the result of executing [$Process value with a default policy$] algorithm, with the following arguments:

    * {{TrustedScript}} as |expectedType|
    * |request|'s [=request/clients=]'s [=environment settings object/global object=] as |global|
    * |encodedScriptSource| as |input|
    * `"Location.href"` as |sink|

    If that algorithm threw an error or |convertedScriptSource| is not a {{TrustedScript}} object, return "Blocked" and abort further steps.
1. Set |urlString| to be the result of prepending `"javascript:"` to stringified |convertedScriptSource|.
1. Let |newURL| be the result of running the [=URL parser=] on |urlString|. If the parser returns a failure, return `"Blocked"` and abort further steps.
1. Set |request|'s [=request/url=] to |newURL|.

     Note: No other CSP directives operate on `javascript:` URLs in a pre-navigation check. Other directives that check javascript: URLs
           will operate on the modified URL later, in the [=inline check=].
1. Return `"Allowed"`.


### <dfn lt="trusted-types-directive">trusted-types</dfn> directive ### {#trusted-types-csp-directive}

This document defines *trusted-types* - a new [[CSP3#directives|Content Security Policy directive]]. The {{#trusted-types-directive|trusted-types}} directive controls the creation of Trusted Type [=policies=].

The syntax for the directive's [=directive/name=] and [=directive/value=] is described by the following
ABNF:

<pre>
directive-name = "trusted-types"
directive-value = <a>serialized-tt-configuration</a>
<dfn>serialized-tt-configuration</dfn> = ( <a>tt-expression</a> *( <a href="https://w3c.github.io/webappsec-csp/#grammardef-required-ascii-whitespace">required-ascii-whitespace</a> <a>tt-expression</a> ) )
<dfn>tt-expression</dfn> = <a>tt-policy-name</a>  / <a>tt-keyword</a>
<dfn>tt-policy-name</dfn> = 1*( <a href="https://tools.ietf.org/html/rfc5234#appendix-B.1">ALPHA</a> / <a href="https://tools.ietf.org/html/rfc5234#appendix-B.1">DIGIT</a> / "-" / "#" / "=" / "_" / "/" / "@" / "." / "%")
<dfn>tt-keyword</dfn> = "'allow-duplicates'"
</pre>

<div class="example" id="whitelist-of-policy-names-in-header">
Types are enforced at sinks, and only two policies may be created: “one” and “two”.

<pre class="http">
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types one two
</pre>
</div>

<div class="example" id="header-that-allows-no-policy-names">
An empty [=directive=] [=directive/value=] indicates policies may not be created,
and sinks expect Trusted Type values, i.e. no DOM XSS [=injection sinks=] can be used
at all.

<pre class="http">
Content-Security-Policy: trusted-types; require-trusted-types-for 'script'
</pre>
</div>

Keyword `'allow-duplicates'` allows for creating policies with a name that was already used.

<div class="example" id="allow-duplicates-in-header">
<pre class="http">
Content-Security-Policy: trusted-types foo bar 'allow-duplicates'
</pre>
</div>

If the policy named `default` is present in the list, it refers to the
[=default policy=]. All strings passed to [=injection sinks=] will be passed through it instead
of being rejected outright.

<div class="example" id="default-in-header">
<pre class="http">
Content-Security-Policy: trusted-types one two default
</pre>
</div>


### <dfn abstract-op>Should sink type mismatch violation be blocked by Content Security Policy?</dfn> ### {#should-block-sink-type-mismatch}

Given a [=Realm/global object=] (|global|), a string (|sink|), a string (|sinkGroup|) and a string (|source|) this algorithm
returns `"Blocked"` if the [=injection sink=] requires a [=Trusted Type=], and
`"Allowed"` otherwise.

1.  Let |result| be `"Allowed"`.
1.  For each |policy| in |global|'s <a>CSP list</a>:
    1.  If |policy|'s <a>directive set</a> does not contain a <a>directive</a>
        which [=directive/name=] is `"require-trusted-types-for"`, skip to the next |policy|.
    1.  Let |directive| be the |policy|'s |directive set|'s [=directive=] which name
        is `"require-trusted-types-for"`
    1.  If |directive|'s [=directive/value=] does not contain a <a>trusted-types-sink-group</a> which is a match
        for a value |sinkGroup|, skip to the next |policy|.
    1.  Let |violation| be the result of executing
        [[CSP#create-violation-for-global|Create a violation object for global, policy, and directive]]
        on |global|, |policy| and `"require-trusted-types-for"`
    1. Set |violation|'s [=violation/resource=] to `"trusted-types-sink"`.
    1. Let |trimmedSource| be the substring of |source|, containing its first 40 characters.
    1. Set |violation|'s [=violation/sample=] to be the result of [=concatenating=] the list &laquo; |sink|, |trimmedSource| &laquo; using space (`"\x20"`) as a |separator|.
    1.  Execute [[CSP#report-violation|Report a violation]] on |violation|.
    1.  If |policy|'s [=policy/disposition=] is `"enforce"`, then set |result| to
        `"Blocked"`.
1. Return |result|.

### <dfn abstract-op>Should Trusted Type policy creation be blocked by Content Security Policy?</dfn> ### {#should-block-create-policy}

Given a [=Realm/global object=] (|global|), a string (|policyName|) and a list of
strings (|createdPolicyNames|), this algorithm returns `"Blocked"` if the
[=Trusted Type Policy=] should not be created, and `"Allowed"` otherwise.

1.  Let |result| be `"Allowed"`.
1.  For each |policy| in |global|'s <a>CSP list</a>:
    1.  Let |createViolation| be false.
    1.  If |policy|'s <a>directive set</a> does not contain a <a>directive</a>
        which name is `"trusted-types"`, skip to the next |policy|.
    1.  Let |directive| be the |policy|'s |directive set|'s [=directive=] which name
        is `"trusted-types"`
    1.  If |createdPolicyNames| contains |policyName| and |directive|'s [=directive/value=] does not contain a <a>tt-keyword</a> which is a match
        for a value `'allow-duplicates'`, set |createViolation| to true.

        Note: `trusted-types policyA policyB 'allow-duplicates'` allows authors to create policies with
        duplicated names.
    1.  If |directive|'s [=directive/value=] does not contain a <a>tt-policy-name</a>,
        which value is |policyName|, set |createViolation| to true.
    1.  If |createViolation| is false, skip to the next |policy|.
    1.  Let |violation| be the result of executing
        [[CSP#create-violation-for-global|Create a violation object for global, policy, and directive]] on |global|, |policy| and
        `"trusted-types"`
    1. Set |violation|'s [=violation/resource=] to `"trusted-types-policy"`.
    1. Set |violation|'s [=violation/sample=] to the substring of |policyName|, containing its first 40 characters.
    1.  Execute [[CSP#report-violation|Report a violation]] on |violation|.
    1.  If |policy|'s [=policy/disposition=] is `"enforce"`, then set |result| to
        `"Blocked"`.
1. Return |result|.

### Violation object changes ### {#csp-violation-object-hdr}

[=violation|Violation=] object [=violation/resource=] also allows `"trusted-types-policy"`
and `"trusted-types-sink"` as values.

### Support for eval(TrustedScript) ### {#csp-eval}

This document modifies the [[CSP3#can-compile-strings|EnsureCSPDoesNotBlockStringCompilation]]
which is reproduced in its entirety below with additions and deletions.

Note: See <a href="https://github.com/tc39/ecma262/issues/938">TC39/ecma262 issue #938</a>
(adding the value to be compiled to algorithm parameters).

<div class="note">Note: EcmaScript code may call `Function()` and `eval` cross realm.
<pre highlight="js">
  let f = new self.top.Function(source);
</pre>
In this case, the |callerRealm|'s Window is `self` and the |calleeRealm|'s Window is `self.top`.
The Trusted Types portion of this algorithm uses |calleeRealm| for consistency with other sinks.
<pre highlight="js">
  // Assigning a string to another Realm's DOM sink uses that Realm's default policy.
  self.top.body.innerHTML = 'Hello, World!';
  // Using another Realm's builtin Function constructor should analogously use that
  // Realm's default policy.
  new self.top.Function('alert(1)')()
</pre>
This is subtly different from the CSP directive enforcement portion which rejects if either
the |calleeRealm| or |callerRealm|'s Content-Security-Policy rejects string compilation.
</div>

Given two [[ECMASCRIPT#realm|realms]] (|callerRealm| and
|calleeRealm|), and a <del>string</del> <ins>value</ins>
(|source|), this algorithm returns <del>normally</del>
<ins>the source string to compile</ins> if compilation is allowed, and
throws an "`EvalError`" if not:

1.  <ins>Let |sourceString| be the result of executing the
    [$Get Trusted Type compliant string$] algorithm, with:
    *   |calleeRealm| as |global|,
    *   |source| as |input|,
    *   `eval` as |sink|,
    *   `'script'` as |sinkGroup|,
    *   {{TrustedScript}} as |expectedType|.</ins>

2.  <ins>If the algorithm throws an error, throw an {{EvalError}}.</ins>

3.  Let |globals| be a list containing |calleeRealm|'s [=Realm/global object=] and |calleeRealm|'s
    [=Realm/global object=].

4.  For each |global| in |globals|:

    1.  Let |result| be "`Allowed`".

    2.  For each |policy| in |global|'s [[CSP#global-object-csp-list|CSP list]]:

        1.  Let |source-list| be `null`.

        2.  If |policy| contains a [=directive=] whose [=directive/name=] is "`script-src`", then
            set |source-list| to that [=directive=]'s [=directive/value=].

            Otherwise if |policy| contains a [=directive=] whose [=directive/name=] is
            "`default-src`", then set |source-list| to that directive's [=directive/value=].

        3.  If |source-list| is not `null`, and does not contain a [=source expression=] which is
            an [=ASCII case-insensitive=] match for the string "<a grammar>`'unsafe-eval'`</a>" then:

            1.  Let |violation| be the result of executing [[CSP3#create-violation-for-global]] on
                |global|, |policy|, and "`script-src`".

            2.  Set |violation|'s [=violation/resource=] to "`inline`".

            3.  If |source-list| [=list/contains=] the expression
                "<a grammar>`'report-sample'`</a>", then set |violation|'s [=violation/sample=] to
                the substring of <del>|source|</del> <ins>|sourceString|</ins> containing its first
                40 characters.

            4.  Execute [[CSP3#report-violation]] on |violation|.

            5.  If |policy|'s [=policy/disposition=] is "`enforce`", then set |result| to
                "`Blocked`".

    3.  If |result| is "`Blocked`", throw an `EvalError` exception.

6. <ins>Return |sourceString|.</ins>

Note: returning |sourceString| means that the string that gets
compiled is that returned by any [=default policy=] in the course of
executing [$Get Trusted Type compliant string$].

Issue: This depends on a solution to
<a href="https://github.com/w3c/webappsec-trusted-types/issues/144">issue #144</a> like <a
href="https://github.com/tc39-transfer/dynamic-code-brand-checks#problem-host-callout-does-not-receive-type-information">TC39 HostBeforeCompile</a>

Issue: In some cases, the violation "`'report-sample'`" contain the result of
applying the default policy to a string argument which differs.
Specifically when, there is a [=default policy=], |isExempt| is false,
and |source| there is a CSP policy for either the |callerRealm|
or |callerRealm| that disallows "`'unsafe-eval'"`.
Is this a feature or a bug?

Note: The previous algorithm reports violations via both report-uris where
callerRealm != calleeRealm.  If [$Get Trusted Type compliant string$] reports an
error, it only reports it via its |calleeRealm|'s report-uri.

# Security Considerations # {#security-considerations}

Trusted Types are not intended to protect access to [=injection sinks=] in an
actively malicious execution environment. It's assumed that the application is
written by non-malicious authors; the intent is to prevent developer mistakes
that could result in security bugs, and not to defend against first-party
malicious code actively trying to bypass policy restrictions. Below we enumerate
already identified vectors that remain risky even in environments with enforced
Trusted Types.

## Cross-document vectors ## {#cross-document-vectors}

While the code running in a window in which Trusted Types are enforced cannot
dynamically create nodes that would bypass the policy restrictions, it is
possible that such nodes can be imported or adopted from documents in other
windows, that don't have the same set of restrictions. In essence - it is
possible to bypass Trusted Types if a malicious author creates a setup in which
a restricted document colludes with an unrestricted one.

CSP propagation rules (see [[CSP3#initialize-document-csp]] partially address this
issue, as new [=local scheme=] documents will inherit the same set of restrictions.
To address this issue comprehensively, other mechanisms like
<a href="https://wicg.github.io/origin-policy/">Origin Policy</a>
should be used to ensure that baseline security rules are applied for the whole
origin.

## Deprecated features ## {#deprecated-features}

Some long-deprecated and rarely used plaform features are not subject to Trusted
Types, and could potentially be used by malicious authors to overcome the
restrictions:

* <a href="https://w3c.github.io/webcomponents/spec/imports/">HTML imports</a>

## Best practices for policy design ## {#best-practices-for-policy-design}

Trusted Types limit the scope of the code that can introduce
vulnerabilities via [=injection sinks=] to the implementation of [=policies=].
In this design, insecure policies can still expose [=injection sinks=] to untrusted data.
Special emphasis needs to be taken by use policies that are either secure for all
possible inputs, or limit the access to insecure policies, such that they are only
called with non-attacker controlled inputs.

As policies are custom JavaScript code, they may be written in a way that heavily
depends on a global state. We advise against this. The policies should
be self-contained as much as possible. All objects that may alter security decisions
a policy makes effectively *become* the policy, and should be guarded & reviewed
together.

Issue: Refer to the external document on secure policy design.

# Implementation Considerations # {#implementation-considerations}

## Vendor-specific Extensions and Addons ## {#vendor-specific-extensions-and-addons}

Restriction imposed by Trusted Types SHOULD
NOT interfere with the operation of user-agent features like addons,
extensions, or bookmarklets. These kinds of features generally advance
the user’s priority over page authors, as espoused in
[[html-design-principles]]. Specifically, extensions SHOULD be able to pass strings
to the [=injection sinks=] without triggering [=default policy=]
execution, violation generation, or the rejection of the value.
